PHP — Searching for a key in an array and searching for a value in an array.
Sep 3, 2018 · 1 min read

To Search for a value in a PHP array,we use php’s in_array() function.
Example :
<?php $arr=[1,2,3];
if(in_array(1,$arr)){
echo "Found";
}
else{
echo "Not found";
} // Output : Found?>
in_array() accepts three parameters,if put in simple words the function is in_array($whatToSearch,$array,$strict) and returns TRUE if $whatToSearch is found in the $array,if not FALSE.
$strict is set to FALSE by default,when set to TRUE, in_array() checks the type of $whatToSearch.
Example :
<?php $arr=[1,2,3];
if(in_array("1",$arr,TRUE)){
echo "Found";
}
else{
echo "Not found";
} // Output : Not Found?>
To search for a key in a PHP array,we use php’s array_key_exists() function.
It accepts two parameters $whatToSearch ,$array and returns TRUE if the key is in the array,otherwise FALSE.
<?php $arr=array(
"code"=>200,
"message"=>"OK"
);
if(array_key_exists("code",$arr)){
echo "Found";
}
else{
echo "Not found";
}// Output : Found
?>
An example where both php’s in_array() and array_key_exists() are used.
Clap it,if you like it :)
