I have an array:
Array ( [A] => 4 [B] => 4 [D] => 4 [E] => 8 [F] => 4 [G] => 8 [H] => 8 [J] => 12 [K] => 12 [L] => 11 [M] => 11 [O] => 10 [P] => 10 [Q] => 10 [R] => 10 )
It had more values, but I filtered out the zero values, because I don't need them.
Now I need every other value, so that I get:
Array ( [A] => 4 [D] => 4 [F] => 4 [H] => 8 [K] => 12 [M] => 11 [P] => 10 [R] => 10 )
I also need the remaining array with the keys intact
Array ( [B] => 4 [E] => 8 [G] => 8 [J] => 12 [L] => 11 [O] => 10 [Q] => 10 )
How can I possibly do this?
The length of the array is subjectible to change. Also the zero values can change.
Try as
$arr = Array ( 'A' => 4, 'B' => 4, 'D' => 4, 'E' => 8, 'F' => 4, 'G' => 8, 'H' => 8, 'J' => 12, 'K' => 12, 'L' => 11, 'M' => 11, 'O' => 10, 'P' => 10, 'Q' => 10, 'R' => 10 );
$arr1 = array();
$arr2 = array();
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr1[$key] = $value;
}else{
$arr2[$key] = $value;
}
$i++;
}
Using array_walk
function
$current = 0;
array_walk($arr,function($v,$k) use(&$result,&$current){
if($current%2 == 0) {
$result['even'][$k] = $v;
}else{
$result['odd'][$k] = $v;
}
$current++;
});
print_r($result);
Fiddle
Fiddle(array_walk)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With