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.
From stackoverflow
-
foreach($arr as $key => $value) if($key&1) unset($arr[$key]);
Instead
if($key&1)
you can useif(!($key&1))
mofle : This removes every odd number, like [1] and [3]. How can I remove every even number, like [0], [2]...?artlung : just change the if statement in Thinker's code to (!$key&1) ... foreach($arr as $key => $value) if(!$key&1) unset($arr[$key]);mofle : 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?Thinker : If !$key&1 not works it is because operator precedence. I edited my code.mofle : Thanks, it works now ;) -
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;')))
Matt : create_function is not recommended as it has a memory leak.Ross : 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)v3 : Awesome, anonymous functions! Didn't know that they were planned, thanks -
I'd do it like this...
for($i = 0; $i < count($array); $i++) { if($i % 2) // OR if(!($i % 2)) { unset($array[$i]); } }
v3 : I think that should be a < instead of a <=Kieran Hall : Ah yes, my mistake. -
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);
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.