Just a bit of fun, wondered which of these people like best for checking if an array is empty in #php? There's (debatably :D) no right answer...

#1 is short
#2 and #3 are very readable

Leaning towards #2 myself!

Hopefully I typed the example code properly lol. xD

@scottwhat I generally use 1, because I'm lazy. Arguably 3 is most correct(tm). Don't use 2.
@Crell @scottwhat why don't you recommend 2?
@Crell @scottwhat all those tutorials are based on an era before 8.0, implying hardly any type hinting. Code written these days ought to have clear type hinting and using empty on an array in that case makes perfectly sense from a readability side. Then take into consideration performance as well https://stackoverflow.com/a/2216159
Checking for empty arrays: count vs empty

This question on 'How to tell if a PHP array is empty' had me thinking of this question Is there a reason that count should be used instead of empty when determining if an array is empty or not? My

Stack Overflow
@luceos @scottwhat Perf benchmarks have changed even more than typing. And the engine folks routinely make improvements so such micro optimizations are backwards from what they were previously. I wouldn't trust benchmarks from the 5.x era for anything. The engine was half rewritten since then.

@Crell @scottwhat recent benchmarks show the same results though, aside from the loose type checking, empty is fastest with the logical NOT having similar results. The strict comparison is slightly faster than count, but not faster than empty.

I personally hold on to using empty, as type hinting should be a standard nowadays in agreement to: https://phpc.social/@Crell/114869999327725709

Recent php 8.3 performance comparison: https://benjamincrozat.com/php-array-empty

Larry Garfield (@[email protected])

It's 2025. If your library still doesn't have types in it (parameter, return, and property), I assume it's abandoned and I should not use it. There are no exceptions to this statement. Not typing your PHP code in 2025 is irresponsible. No, docblocks are not good enough. #PHP

PHP Community on Mastodon