Reputation: 133
I try to get the array key of matching values. It looks like that:
$someId = 2
$array[0][id] = "1";
$array[0][firstname] = "dude1";
$array[1][id] = "2";
$array[1][firstname] = "dude2";
$array[2][id] = "3";
$array[2][firstname] = "dude3";
How I get the array key e.g. "1" ($array[1]), by matching the var "$someId = 2" with the unique IDs ( $array[1][id]) in the array?
Basically: $someId === $array[x][id] > returns the array $array[x] where it matches.
Upvotes: 1
Views: 221
Reputation: 212402
array_filter() retains associativity
$result = array_filter(
$array,
function ($item) use ($personId) {
return ($item['id'] == $personId);
}
);
var_dump(array_keys($result));
Upvotes: 1
Reputation: 64526
A simple foreach
will do it:
$someId = 2;
foreach($array as $person)
{
if($person['id'] == $someId)
{
// found a match, do something with $person
// ...
break; // remove the break if you want to continue searching after a match
}
}
If you want the key then change to
foreach($array as $key => $person)
Upvotes: 2