Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP split array based on value [duplicate]

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.

like image 843
Dan Mooray Avatar asked Oct 28 '25 05:10

Dan Mooray


1 Answers

$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)
)
like image 75
Ricardo Alvaro Lohmann Avatar answered Oct 29 '25 18:10

Ricardo Alvaro Lohmann