Explode empty string returns one-element array

Pretty annoying, exploding an empty string with – for example space – returns an array with one element, indexed with 0 and containing an empty string:

$string = "";
explode(" ", $string);

returns

array(
  [0] => ''
)

There is a simple workaround that also removes the unnecessary empty elements – array_filter(). This function removes all the array elements whose values evaluate to boolean false:

array_filter(explode(" ", $string));

Returns:

array(
)

Leave a Reply

Your email address will not be published. Required fields are marked *