1

Is there a split function in PHP that works similar to the JavaScript split()? For some reason explode() returns an array of length 1 when an empty string is given.

Example:

$aList = explode(",", "");    -> to return a 0-length array
$aList = explode(",", "1");   -> to return a 1-length array  $aList[0] = 1
$aList = explode(",", "1,5"); -> to return a 2-length array  $aList[0] = 1 and $aList[1] = 5
3
  • 4
    Try using preg_split('~,~',$some_string,-1,PREG_SPLIT_NO_EMPTY) with the PREG_SPLIT_NO_EMPTY flag. php.net/manual/en/function.preg-split.php Commented Dec 1, 2020 at 1:02
  • 1
    Any split or explode will return 1. Loigcally, thats all there is left. Cant "split" by what does not exists. So the return is the original value on set. Commented Dec 1, 2020 at 1:06
  • Thanks @bassxzero. That seems like it did the trick! Commented Dec 1, 2020 at 1:16

3 Answers 3

2

I have two suggestion for you

1. check empty string before explode

if( strlen($str) ){
    $aList = explode(",", $str);
}

2. use empty method to check array

$aList = explode(",", $str);

if( empty($aList) ){}

if( !empty($aList) ){}
Sign up to request clarification or add additional context in comments.

3 Comments

That seems like a lot of work when it comes to using $aList throughout the rest of the code.
yes ofcurse, but i dont know a better way
preg_split('~,~',$some_string,-1,PREG_SPLIT_NO_EMPTY) looks uglier but does the trick. Thanks to @bassxzero
0

How about

$aList = empty($aString) ? [] : explode(',', $aString)

However, the comment by @bassxzero using preg_split also looks nice.

Comments

-1

All you have to do is check the return value of "explode()":

https://www.php.net/manual/en/function.explode.php

If delimiter is an empty string (""), explode() will return FALSE.

PS:

Q: What's the rationale for "array of 1"?

A string that doesn't contain the delimiter will simply return a one-length array of the original string (here, an "empty"string).

"GetSet" put it very well in his comment above:

Any split or explode will return 1. Logically, that's all there is left.

2 Comments

The delimiter is not empty. The subject string can be empty
Dude - nobody said the delimiter wasn't empty.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.