The reason why your in_array is not working is because your values 6
, 5
and 8
are stored inside another array in your main array.
So to search for a value, you could loop through each array with a function:
Non-recursive (1 level depth search)
function searchInArray($array, $value){
// If the array parameter is not an array and the value parameter is an array, return false
if(!is_array($array) || is_array($value))
return false;
// If the value is found in the main array, return true
if(in_array($value, $array))
return true;
// Loop through each subarray
foreach($array as $subarray){
if(in_array($value, $subarray))
return true;
}
}
Let's say this is your array:
$array = [[6], [5], [8]];
And if we var_dump with var_dump(searchInArray($array, 8));
the result:
bool(true)
Recursive (infinite depth search)
With this function, it will search inside each subarray... which is a recursive function:
function recursiveSearch($array, $value){
// If the array parameter is not an array and the value parameter is an array, return false
if(!is_array($array) || is_array($value))
return false;
// If the value is found in the main array, return true
if(in_array($value, $array))
return true;
// Loop through each subarray and make a recursive call
foreach($array as $subarray){
if(recursiveSearch($subarray, $value))
return true;
}
return false;
}
So let's suppose this time this is your array:
$array = [[6], [5], [8, [9]]];
The result:
var_dump(recursiveSearch($array, 4)); // false
var_dump(recursiveSearch($array, 8)); // true
var_dump(recursiveSearch($array, 9)); // true