Friday, 10 August 2018

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. $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)
  3.  
  4. <p>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.</p>
  5.  
  6. <code class="php">$string = 'this is a string';
  7. if(!isset($string{20})){
  8. // stringtoo short
  9. }</code>
  10.  
  11. <p>Because isset() is a language construct it works quicker than strlen() so this comparison has almost no overhead at all.</p>

0 comments:

Post a Comment