var_dump(count(explode(',',[]))); // 0
var_dump(count(explode(',',''))); // 1
var_dump(count(explode(',',null))); // 1 ????
I was expecting 0 for the last one. Can someone tell me the reason why exploding from null
is 1 and not 0? (PHP 5.6.16)
The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.
explode(string $separator , string $string , int $limit = PHP_INT_MAX ): array. Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .
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 == ''
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With