Check the value - in_array() for multidimensional array in PHP

How can I check if the value is included in multidimensional array in PHP ? I need an in_array() function equivalent for multidimensional array.
0
give a positive ratinggive a negative rating
11 Oct 2020 at 02:52 PM
Hi,

To check if the value is included in mutlidimensional array, you can use the solution below. The function is calling itself to check if the value is included in sub-arrays. Please note that it is checking the array values, but not the array keys.


function in_multidimensional_array($value, $multidimensional_array) {
foreach ($multidimensional_array as $array_value) {
if ( $array_value == $value OR ( is_array($array_value) AND in_multidimensional_array($value, $array_value) ) ) {
return true;
}
}
return false;
}

$arr = array(1 => array("abc","def"), 2 => array("aaa","bbb"));

if ( in_multidimensional_array("aaa",$arr) ) {
echo "Value is included in array.";
}
else {
echo "Value is not included in array.";
}


0
give a positive ratinggive a negative rating
28 Nov 2020 at 12:24 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us