Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get every other value of array in PHP

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.

like image 340
Fl1p Avatar asked Jun 10 '15 09:06

Fl1p


1 Answers

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)

like image 76
Narendrasingh Sisodia Avatar answered Nov 11 '22 22:11

Narendrasingh Sisodia