Use isset() Instead of strlen()

This tip is courtesy of a great article, 10 Advanced PHP Tips Revisited

When referencing an array’s value via a numeric key, you follow the variable name ($variable) with the numeric index, enclosed by square brackets [5]. e.g. $variable[5] = ‘value’
However, when $variable represents a string, using the same syntax will return a string with the character at the position specified by the numeric index (0 marks the first character in the $variable string). An example:

$string = 'abcdefg';
var_dump($string[2]);

Output: string(1) “c”

Where this comes into play is when using isset() rather than strlen(). Consider the following example:

$string = 'abcdefg';
if (isset($string[5])){
  echo $string[5].' found!';
}

Output: f found!

$string = 'abcdefg';
if (isset($string[7])){
     echo $string[7].' found!';
  }else{
     echo 'No character found at position 7!';
}

Output: No character found at position 7!

This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” It’s little tricks like this that will keep your code lean and efficient. Thanks to Chris Shiflett and Sean Coates for their contributions to the referenced article.

Similar Posts: