28 January, 2011

Check value exists in multidimensional array

Most of the times we are playing with arrays in php. And it can be troublesome when we have to check for value in multidimensional array. I get into such a situation every often. I used to loop through the array to check for the existence of value.

So, i thought of making a function that checked for the existence of a value in a multi array. I am much happier using this function rather than looping through arrays making my time worse.

Following code simplifies checking of a value in multi-array in php.

//function to check if a values exists in multidimensional array
function in_multi($searchFor, $array) {
foreach($array as $key => $value) {
if($value == $searchFor) {
return true;
}
else {
if(is_array($value)) if(in_multi($searchFor, $value)) return true;
}
}
return false;
}
//test array
$testArr = array(
0 => array(
0 => array(
"10" => 20,
"20" => 40
),
1 => array(
"a" => 555,
"b" => 152
)
),
1 => array(
0 => 999,
1 => 2024
)
);


$isThere = in_multi(152, $testArr);
if($isThere) {
echo "Found";
}
else {
echo "Not Found";
}
?>
And we are done.

1 comment:

Anonymous said...

Hi Author Thanks very much to post like this unique article.

It works for me . Again post like this type of unique article.

Thanks again. Chears