filter by even and odd key

Hello All.
I’m curious what is true PHP-way to solve simple task like obtaining of elements of array by it’s numeric keys(even or odds). I’ve tried use array_filter( on php.net here is completed example ) with recommended flag ARRAY_FILTER_USE_KEY - but there is not effect.

Thanks

This works fine here, are you sure you’re running PHP >= 5.6?

[php]$array = [
1 => ‘foo’,
2 => ‘bar’,
3 => ‘foo’,
4 => ‘bar’,
5 => ‘foo’,
6 => ‘bar’,
7 => ‘foo’,
8 => ‘bar’,
9 => ‘foo’,
10 => ‘bar’,
11 => ‘foo’,
12 => ‘bar’,
13 => ‘foo’,
14 => ‘bar’,
15 => ‘foo’,
16 => ‘bar’
];

function getOddOrEvenFromArray($oddOrEven = ‘odd’, $array = [])
{
return array_filter(
$array,
function ($key) use ($oddOrEven) {
return $key % 2 === ($oddOrEven === ‘odd’ ? 1 : 0);
},
ARRAY_FILTER_USE_KEY
);
}

echo ‘

’;
print_r(getOddOrEvenFromArray(‘even’, $array));[/php]

[hr]

other than that array_filter just loops through the array, so you can just as well just foreach and return values of even keys.

Sponsor our Newsletter | Privacy Policy | Terms of Service