Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does explode on null return 1 element?

Tags:

php

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)

like image 343
azngunit81 Avatar asked Apr 15 '16 13:04

azngunit81


People also ask

What does the explode () function return?

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.

What does the explode () function do?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.

What is explode in laravel?

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 .


2 Answers

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 == ''

like image 193
Peter Avatar answered Oct 01 '22 07:10

Peter


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.

like image 26
bishop Avatar answered Oct 01 '22 06:10

bishop