0

I want explode to return an empty array if the delimiter is not found.

Currently, I do something like this to get the explode behavior I want:

            if (strpos($line, ' ') === false) {
                $entries = [];
            } else {
                $entries = explode(' ', $line);
            }

There must be a more concise way of getting this behavior without having to use preg_split. preg_split has its own behavior that is also undesirable, such as including the delimiter in the resultant array entries.

tau
  • 6,499
  • 10
  • 37
  • 60

1 Answers1

2

So, you have a string of space delimited data, e.g. 'foo bar'? Your rule is if there's no delimiter, meaning if the string is either a single value ('foo') or an empty string (''), then you want an empty array; otherwise you want the split delimited data?

$entries = explode(' ', $line);
if (count($entries) < 2) {
    $entries = [];
}

There isn't really a sane way to make this specific condition shorter, but this removes the redundant inspection of the string and clearly states what the code is trying to do.

deceze
  • 510,633
  • 85
  • 743
  • 889