PHP — Searching for a key in an array and searching for a value in an array.

Din Esh
Din Esh
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 :)

Din Esh

Written by

Din Esh

All about Full stack development https://www.thewebblinders.in/programming/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade