Faster Way Of Checking String Length With PHP

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.
CAPTCHA
1 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.