Why does explode on null return 1 element?
explode
takes a string as its second argument, by specification. You gave it a null
, so before the logic of explode
runs, PHP converts the null
into a string. Every function operates this way: if the arguments don't match the formal specification, PHP attempts to "type juggle" until they do. If PHP can juggle, the engine motors along happily, otherwise you get a weak slap on the wrist:
PHP Warning: explode() expects parameter 2 to be string, object given in file.php on line 1
The way PHP juggles null to string is simple: null := ''
. So a call with null
and a call with ''
are semantically equivalent because of type juggling, as seen here:
$a = explode(',', '');
$b = explode(',', null);
var_dump($a === $b); // true
$a = count(explode(',', ''));
$b = count(explode(',', null));
var_dump($a === $b); // true
So now you might ask: why does PHP return a one-element array when exploding on an empty string? That is also by specification:
If delimiter contains a value that is not contained in string ... an array containing string will be returned.
As a workaround, use
array_filter(explode(',', $myvar));
Then you get an empty array and count()
will return 0. Be aware, that it will also return an empty array, when $myvar == ''