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

Exploding an empty string should return an empty array. No matter what biased logic do we follow.

A simple (but buggy) workaround is to remove the unnecessary empty elements by using array_filter(). This function removes all the array elements whose values evaluate to Boolean false:

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

Returns:

array(
)

Unfortunately “0” evaluates to false as well, therefore calling

array_filter(explode(" ", "0 0"));

Returns an empty array!

An elegant (but not the fastest) solution is a feature-rich version of explode():

public function explode2(string $by, string $string, array $options = []):array {
    $includeEmpty = boolval($options['include_empty'] ?? false);
    $trimChars = strval($options['trim_chars'] ?? " \n\r\t\v\x00");
    $result = [];
    foreach (explode($by, $string) as $raw) {
        $trimmed = trim($raw, $trimChars);
        if ($includeEmpty || strlen($trimmed)) {
            $result[] = $trimmed;
        }
    }
    return $result;
}

Leave a Reply

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