10

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

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

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.

7 Answers 7

17

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))

Sign up to request clarification or add additional context in comments.

5 Comments

This removes every odd number, like [1] and [3]. How can I remove every even number, like [0], [2]...?
just change the if statement in Thinker's code to (!$key&1) ... foreach($arr as $key => $value) if(!$key&1) unset($arr[$key]);
That's what I thought too, but it gives me [1],[2],[3], but not the [4], it should only give me [1] and [3]. Any thoughts?
If !$key&1 not works it is because operator precedence. I edited my code.
what "&" is actually doing in if($key&1) ...And How it knows whether it is ODD or EVEN
2

Here's a "hax" solution:

Use array_filter in combination with an "isodd" function.

array_filter seems only to work on values, so you can first array_flip and then use array_filter.

array_flip(array_filter(array_flip($data), create_function('$a','return $a%2;')))

4 Comments

create_function is not recommended as it has a memory leak.
And they're hard to read as well :) Anonymous functions would be worth looking at for when 5.3.0 is released (uk2.php.net/manual/en/functions.anonymous.php)
Awesome, anonymous functions! Didn't know that they were planned, thanks
Because array_filter() has evolved to enjoy ARRAY_FILTER_USE_KEY there is no need for this "hax" solution. No one should be using this for any reason in modern PHP development.
2

You could also use SPL FilterIterator like this:

class IndexFilter extends FilterIterator {
    public function __construct (array $data) {
        parent::__construct(new ArrayIterator($data));
    }   

    public function accept () {
        # return even keys only
        return !($this->key() % 2);
    }     
}

$arr      = array('string1', 'string2', 'string3', 'string4');
$filtered = array();

foreach (new IndexFilter($arr) as $key => $value) {
    $filtered[$key] = $value;
}

print_r($filtered);

Comments

1
<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Comments

0

I'd do it like this...

for($i = 0; $i < count($array); $i++)
{
    if($i % 2) // OR if(!($i % 2))
    {
        unset($array[$i]);
    }
}

1 Comment

I think that should be a < instead of a <=
0
<?php 
$array = array(0, 3, 5, 7, 20, 10, 99,21, 14, 23, 46); 
for ($i = 0; $i < count($array); $i++) 

{ 
        if ($array[$i]%2 !=0)
        echo $array[$i]."<br>";
}
?> 

Comments

0
$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.