A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2009 yearFilter array - odd even - page 1
User InfoPosts
Filter array - odd even#1
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.

posted date: 2009-04-10 08:31:00


Re: Filter array - odd even#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2009-04-10 08:31:01


Re: Filter array - odd even#3
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))

posted date: 2009-04-10 08:36:00


Re: Filter array - odd even#4
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;()))

posted date: 2009-04-10 08:39:00


Re: Filter array - odd even#5
create_function is not recommended as it has a memory leak.

posted date: 2009-04-10 08:52:00


Re: Filter array - odd even#6
This removes every odd number, like [1] and [3]. How can I remove every even number, like [0], [2]...?

posted date: 2009-04-10 10:06:00


Re: Filter array - odd even#7
just change the if statement in Thinker's code to (!$key&1) ... foreach($arr as $key => $value) if(!$key&1) unset($arr[$key]);

posted date: 2009-04-10 10:33:00


Re: Filter array - odd even#8
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?

posted date: 2009-04-10 10:52:00


Re: Filter array - odd even#9
If !$key&1 not works it is because operator precedence. I edited my code.

posted date: 2009-04-10 13:02:00


Re: Filter array - odd even#10
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)

posted date: 2009-04-10 13:07:00


Re: Filter array - odd even#11
I(d do it like this...for($i = 0; $i < count($array); $i++){ if($i % 2) // OR if(!($i % 2)) { unset($array[$i]); }}

posted date: 2009-04-10 13:09:00


Re: Filter array - odd even#12
I think that should be a < instead of a <=

posted date: 2009-04-10 13:42:00


select page: « 1 2 »
Copyright ©2008-2017 www.momige.com, all rights reserved.