DEV Community

Discussion on: 3 tips for performant PHP code

Collapse
 
klnjmm profile image
Jimmy Klein • Edited

I don't agree with some of your points :

  • isset($array['key']) over array_key_exists('key', $array)

isset don't have the same result than array_key_exists. It also test than the value at the key is null. So be careful, you have to know exactly what test you want.
(see my post dev.to/klnjmm/5-bad-habits-to-lose...)

  • > Faster than function calls. There are two language constructs that particularly useful, which are isset and empty.

I don't recommend to use empty. It can cause a lot of bugs because empty test that a variable is false. And a lot of values in PHP is considered as false : null, 0, "", false, [], ...etc.
Instead consider using one of this (you have to know the type of you variable)

if ($var !== null) {}
if ($var !== '') {}
...

Avoid using empty function !

  • if($arr) {} over if(count($arr) > 0) {}

if($arr) {} makes an implicit cast of $arr (same problem than empty function).
If you know that $arr is an array, I prefer count method or if ($arr !== [])

Collapse
 
siimsoni profile image
Kristjan Siimson

Well, it is your job as a programmer to know when you use which language feature. You can't argue that a function is bad because you can use it incorrectly.

Collapse
 
klnjmm profile image
Jimmy Klein

Ok but I think that recommend to other readers (and maybe beginners) to use empty function is not a good thing.

Thread Thread
 
siimsoni profile image
Kristjan Siimson • Edited

True, I've added a disclaimer in beginning of the article.

EDIT: And explained the potential pitfalls associated with these optimizations.