Tag Archives: Function strlen

PHP: isset () vs strlen ()

How to test the length of a string in PHP ?  Well, PHP has a function called strlen () for this purpose.
So obviously, a simple if (strlen ($str) > 10) { ... } should do the trick, isn’t it?

Actually, there’s another way to do that: considering that a string is an array of characters, it’s possible to test if a character is set at the length we want to check with isset (). So the line of code above should be replace by if (isset ($str [10]) { ... }.

Why should we use isset () instead of strlen ()?

Well, it’s way faster: running the test above 100 000 times for each function gives me:
strlen () : 0.034812927246094 seconds
isset () : 0.0079290866851807 seconds