Possible Duplicate:
How to split an array based on a certain value?
Here is an example array I want to split:
(0, 1 ,2 ,3, 0, 4, 5)
How do I split it in 2 array like this?
(0, 1 ,2 ,3) (0, 4, 5)
Basically I want to check if the value of an element is zero and then create an array of all the elements until I find another zero. I can't seem to come up with a solution to this.
First concatenate the elements, then split using
0
and then separate them again by prefixing0
e.g. belowSimilar to a comment,
array_keys
can be used to search for all keys containing the value you search for (zero in your case).You then can loop over these positions and slice the array (see
array_slice
) into the parts.Example (Demo):
This variant even preserves original keys, exemplary
$parts
output:Another alternative could be similar to some other answers outlined. The following variant does preserve keys, too:
Output (Demo):
You'll end with the following.
You can use PHP explode to break up into String arrays for each appearance of 0, but I see now that you have an array, not a string. As suggested above now, you can use the inverse, PHP implode.