Here is an example array I want to split:
(1,2,3,4,5,0,6,7,0,8,9,10,11,12,0)
How do I split it in 3 arrays like this?
(1,2,3,4,5,0) (6,7,0) (8,9,10,11,12,0)
Here is an example array I want to split:
(1,2,3,4,5,0,6,7,0,8,9,10,11,12,0)
How do I split it in 3 arrays like this?
(1,2,3,4,5,0) (6,7,0) (8,9,10,11,12,0)
Here's the solution. (Author said he wants to split at '0' instead of duplicate values)
function split_array_by_duplicate_values($a, $duplicate = 0)
{
$c = array_intersect($a, array($duplicate));
$r = array();
$i = 0;
foreach($c as $k => $v) {
$l = ++$k - $i;
$r[] = array_slice($a, $i, $l);
$i = $k;
}
return $r;
}
$a = array(1,2,3,4,5,0,6,7,0,8,9,10,11,12,0);
print_r(split_array_by_duplicate_values($a));
returns
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 0
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 0
)
[2] => Array
(
[0] => 8
[1] => 9
[2] => 10
[3] => 11
[4] => 12
[5] => 0
)
)