Test it:
foreach (['', null, 0, 0.0, '0', false, [], new stdClass, 'foo', 1, true, ['bar' => 'baz']] as $val) {
var_dump($val, count($val), !empty($val));
echo '-------------', PHP_EOL;
}
It differs for these cases:
string(0) ""
int(1)
bool(false)
-------------
int(0)
int(1)
bool(false)
-------------
float(0)
int(1)
bool(false)
-------------
string(1) "0"
int(1)
bool(false)
-------------
bool(false)
int(1)
bool(false)
Additionally, count
will trigger an error for undefined variables. On PHP 7.2+, count
also triggers an error for any non-Countable
value (which is basically everything except array
or classes that implement Countable
).
So, if you can guarantee that your variable will always be an array, there's no difference. If your variable can be anything other than an array, including undefined, then you'll see anywhere between different results and errors triggered.
If you expect your variable to exist and to be an array/Countable
, you should prefer count
or just if ($variable)
(since an empty array is falsy too) to get proper error messages if your value violates your expectations.