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.

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

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

1
2
3
4
$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.

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

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

Category: 

Share:

  • Add news feed
  • Bookmark this on Delicious

Add new comment