How can a filter out the array entries with an odd or even index number?
Array
(
[0] => string1
[1] => string2
[2] => string3
[3] =&
$array = array(0 => 'string1', 1 => 'string2', 2 => 'string3', 3 => 'string4');
// Removes elements of even-numbered keys
$test1 = array_filter($array, function($key) {
return ($key & 1);
}, ARRAY_FILTER_USE_KEY);
// Removes elements of odd-numbered-keys
$test2 = array_filter($array, function($key) {
return !($key & 1);
}, ARRAY_FILTER_USE_KEY);
This answer is a bit of an improvement over this answer. You can use anonymous functions instead of create_function
. Also, array_filter
takes an optional flag parameter that lets you specify that the callback function takes the key as its only argument. So you don't need to use array_flip
to get an array of keys.