Tuesday, April 7, 2009

PHP: using isset to test string length

When working with strings it is often necessary to check that the string is of a certain minimum or maximum length. The standard practice is to use the strlen function to accomplish this as follows:
if (strlen($password) < 6) { echo "Password too short"; }

This is fine except there's another way to accomplish this using isset and php's ability to access the characters of a string as if it were an array. Since isset is a language construct rather than a function, it is faster then using strlen and might increase performance a bit if your code includes a large number of these calculations (in a loop for instance). Here's the above code using the isset trick:
if (!isset($password{5})) { echo "Password too short"; }

Basically this tests whether the 6th character in the string is set. If it is not, then the string must be less than 6 characters in length.

No comments:

Post a Comment