Faster Way Of Checking String Length With PHP

9th April 2008 - 2 minutes read time

If you want to know the length of a string in PHP you would normally turn to the strlen() function which simply tells you the length of the string.

$string = 'this is a string';
$strLength = strlen($string);

To use this to check the length of the string use the following example.

$string = 'this is a string';
if (strlen($string) < 20) {
 // code here

A quicker way of looking at the length of a string would be to use the isset() function in conjunction with the curly braces {} used for locating character from a string.

$string = 'this is a string';
if (!isset($string{20})) {
 // string too short

Because isset() is a language construct it works quicker than strlen() so this comparison has almost no overhead at all.

Add new comment

The content of this field is kept private and will not be shown publicly.