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.
11 Oct 2020 at 02:52 PM
0pnshow more
StorStor
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.";
}


28 Nov 2020 at 12:24 PM
0pnshow more
TimTim
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook & Twitter
2021 AnswerTabsTermsContact us