<?PHP
$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
$key=array_search("fat",$arr);
echo $key; //nuts
?>
If there are more than one key with the same value, the first occurrence will be returned.
If the
<?PHP
$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
$key=array_search("carbon",$arr);
echo $key; //apple
$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"43","meat"=>"protein");
$key=array_search(43,$arr, true);
echo $key; //no output, 43 and "43" types not match
$key=array_search("43",$arr, true);
echo $key; //nuts
?>
If all keys with the same value need to be retrieved, you can use array_keys() function.
<?PHP
$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
$arr2=array_keys($arr,"carbon");
foreach($arr2 as $element) echo "$element, "; //apple, rice,
$arr2=array_keys($arr,"fat");
foreach($arr2 as $element) echo "$element, "; //nuts,
?>
in_array() checks whether a value is in a array.
<?PHP
$arr=array(1,2,3,4,5,6,7,8,9);
if (in_array(3,$arr)) echo "3 is an array element";
//3 is an array element
$arr=array("2.3",4,9,10);
if (in_array("4",$arr,true)) echo "4 is in the array";
if (in_array(2.3,$arr,true)) echo "2.3 is in the array";
//no output, type not match. "2.3" is string, 2.3 is number
?>