Faster Way Of Checking String Length With PHP

9th April 2008 - 1 minute 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.

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

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

  1. $string = 'this is a string';
  2. if (strlen($string) < 20) {
  3. // code here
  4. }

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.

  1. $string = 'this is a string';
  2. if (!isset($string{20})) {
  3. // string too short
  4. }

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.