tags:

views:

98

answers:

2

I have an array that looks like this:

Array
(
    [0] => Array
        (
            [0] => 1
            [id] => 1
        )

    [1] => Array
        (
            [0] => 2
            [id] => 2
        )
)

What I would like to do is compare an int value against what's in the id value field. So, if I were to pass in say a 1, I'd like to be able to have a function compare this. I was thinking in_array but I can't get that to work. Does anyone know what function I can use for this?

Thanks.

+1  A: 

Try something like this:

$needle = 1;
$found = false;
foreach ($array as $key => $val) {
    if ($val['id'] === 1) {
        $found = $key;
        break;
    }
}
if ($found !== false) {
    echo 'found in $array['.$found.']';
}


Since you want something more compact:

$needle = 1;
array_filter($array, create_function('$val', 'return $val["id"] !== '.var_export($needle, true).';'))

That will filter out all those elements that’s id value is not 1.

Gumbo
Hi Gumbo, Thanks for the hand. Isn't there a php function that can do this? I'm certain that your code would do the trick but I'd like to use a php function if there is one available.
+1  A: 

It's not entirely clear what you'd like the result of the function to be, however I'm guessing you'd like the key of array that contains the ID you are looking for, in that case the following function would find that.

<?php
function get_key($array, $id) {
  foreach ($array as $key => $unit) {
   if ($unit['id'] == $id) {
     return $key;
   }
  }
}
codeincarnate
Hi code. You're right. I'd just like the value returned. I can do a comparison with it then. I'm truly surprised that php doesn't have a built-in function that will handle this.
Thanks for the snippet by the way. I'll give this a shot.
What exactly would it look for in the second level arrays? And what would the function return? How would it handle duplicates? Writing a general function that operated properly would be difficult and having it in the language could be confusing because of all the potential different uses.Because of this, having people do their own seems to make more sense in this case. It's an easy one off function and you get exactly the functionality you want.
codeincarnate