PHP Array Tips - Part 18: Do you want to search an array for a particular key or value? you can use array_key_exists() or in_array(). Like this:
Sample for searching value
<?php
$arr = array("zero","zero","zero","one", "two", "three", "four", "five", "six");
if(in_array("five",$arr)){
echo "found";
}else{
echo "not found";
}
// result found
?>
Sample for searching value and key
<?php
$arr = array("zero","zero","zero","one", "two", "three", "four", "five", "six");
function arraySearch($needle, $haystack){
if(!is_array($haystack)) {
die("second argument is not array");
}
foreach($haystack as $key => $val){
if(preg_match("/$needle/i", $val) || preg_match("/$needle/i", $key)){
return true;
break;
}
}
}
if(arraySearch("zero", $arr)){
echo "found";
}else{
echo "not found";
}
if(arraySearch(4, $arr)){
echo "found";
}else{
echo "not found";
}
?>