PHP split array based on value

Dan Mooray picture Dan Mooray · Dec 13, 2012 · Viewed 10.8k times · Source

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.

Answer

Ricardo Alvaro Lohmann picture Ricardo Alvaro Lohmann · Dec 13, 2012
$array = array(0, 1 ,2 ,3, 0, 4, 5);
$result = array();
$index = -1;
foreach ($array as $number) {
    if ($number == 0) {
        $index++;
    }
    $result[$index][] = $number;
}
echo print_r($result, true);

You'll end with the following.

array(
    0 => array(0, 1, 2, 3),
    1 => array(0, 4, 5)
)