I have an array where I want to search the uid
and get the key of the array.
Assume we have the following 2-dimensional array:
<
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if ($val[$sKey] == $id) {
return $key;
}
}
return false;
}
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
// Array Data Of Users
$userdb = array (
array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);
// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
echo "Search Result can not be found";
}
PHP Fiddle Example