tags:

views:

82

answers:

2

I have an array that looks like:

Array (
    [63] => 0
    [64] => 1
    [65] => 1
    [66] => 0 )

Is there a way to extract the keys for all the values that are equal to 1 (in this case I just want 64 and 65) using Set::extract or Set::remove or some other method?

+2  A: 

One way may be like this:

$new_array = array();

foreach($your_array as $value)
{
  if ($value == 1)
  {
    $new_array[] = $value;
  }
}

print_r($new_array);

Or you can use the array_filter function.

Sarfraz
I am aware of using foreach and am currently doing something similar to this, but I was just wondering if it is possible with the Set class
jimiyash
Yes you can use the array_filter function too.
Sarfraz
Is there a reason you want to use the Set class? array_filter is (probably) going to be the fastest.
Travis Leleu
I just thought using the Set class would be cleaner. I haven't used array_filter before but it looks like if you pass it without a callback argument, it will remove the ones that are 0 because they are equal to false. I'll give it a try.
jimiyash
array_filter worked. wow learn something new everyday.
jimiyash
@Jason: that is great news then :)
Sarfraz
+1  A: 

Sarfrarz is right.. array_filter will be the most efficient solution.

but if you still want to use cakphp's builtin method then you should look at the manual for such things.

http://book.cakephp.org/view/640/Set

Yash