DEV Community

Thai Nguyen Hung
Thai Nguyen Hung

Posted on

Use isset() Instead of strlen()

isset() is faster than using strlen() because calling a function is more expensive than using a language construct.
The isset() method is consistently about 6 times faster.

Test to show the speed http://codepad.org/ztYF0bE3

strlen() over 1000000 iterations 7.5193998813629
isset() over 1000000 iterations 0.29940009117126

Refs:

Top comments (3)

Collapse
 
klnjmm profile image
Jimmy Klein

I think the explanation is a bit short, and that beginners could easily make mistakes.

strlen andisset do not have the same functionality:

  • strlen allows to test the length of a string.
  • isset allows you to test that variable is defined and notnull.

You really need to have a specific performance need to use what is described in the article (ie iterate 1,000,000 times).

In most cases, I prefer to use strlen: if your business need is for example that your password has a minimum length of 8 characters, then the translation in the code will be much more explicit than withisset

if (strlen($password) < 8) {
    // error
}
if (!isset($password[7])) { // what does this "7" mean, the business need asks 8
    // error
}

If you want to test that a string is not empty, it is better I think to do

if ($myString !== '') {

}

rather than

if (!isset($myString[0])) {

}
Collapse
 
emicheldev profile image
e.Michel

Thanks @Jimmy Klein
awesome

Collapse
 
hungthai1401 profile image
Thai Nguyen Hung

Thanks @Jimmy Klein very much