Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array - odd even

Tags:

arrays

php

How can a filter out the array entries with an odd or even index number?

Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] => string4
)

Like, i want it remove the [0] and [2] entries from the array. Or say i have 0,1,2,3,4,5,6,7,8,9 - i would need to remove 0,2,4,6,8.

like image 859
Sindre Sorhus Avatar asked Apr 10 '09 16:04

Sindre Sorhus


1 Answers

foreach($arr as $key => $value) if($key&1) unset($arr[$key]);

The above removes odd number positions from the array, to remove even number positions, use the following:

Instead if($key&1) you can use if(!($key&1))

like image 155
Thinker Avatar answered Sep 29 '22 10:09

Thinker