tags:

views:

735

answers:

4

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.

+2  A: 

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

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

Thinker
This removes every odd number, like [1] and [3]. How can I remove every even number, like [0], [2]...?
mofle
just change the if statement in Thinker's code to (!$key
artlung
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?
mofle
Thinker
Thanks, it works now ;)
mofle
+2  A: 

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;')))
v3
create_function is not recommended as it has a memory leak.
Matt
And they're hard to read as well :) Anonymous functions would be worth looking at for when 5.3.0 is released (http://uk2.php.net/manual/en/functions.anonymous.php)
Ross
Awesome, anonymous functions! Didn't know that they were planned, thanks
v3
A: 

I'd do it like this...

for($i = 0; $i < count($array); $i++)
{
    if($i % 2) // OR if(!($i % 2))
    {
        unset($array[$i]);
    }
}
Kieran Hall
I think that should be a < instead of a <=
v3
Ah yes, my mistake.
Kieran Hall
+1  A: 

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);
Anti Veeranna