Using isset() Instead of strlen() in PHP

I found something interesting in an old Smashing Magazine article. The author describes a slightly faster alternative to the strlen() function in PHP, which is used to determine the length of a string variable.

if (isset($username[5])) {
 // The username is at least six characters long.
}

An interesting fact about PHP is that a string is technically an array of characters. If the $username string is equal to redwall_hp, you could echo out $username[3] and get w.

The code snippet above uses the isset() language construct to see if the sixth array key, the sixth letter, is set. If it is, then the string must be at least six characters long.

For quick checks during form processing, this might save you a few milliseconds here and there in processing time. It wouldn’t work in situations where you need to know the actual number of characters in a string, as opposed to whether it’s more or less than something.

  • http://extraordinaire.me Extraordinaire

    it would actually work to check the length of a string, not the most practical way though :)

    $str = 'mystring';

    $i = 0;
    while(isset($str[$i]))
    {
    $i++;
    }

    • http://intensedebate.com/people/redwall_hp redwall_hp

      Yeah, not very practical, is it? Bringing a loop into the equation would probably negate any speed benefits. :D