I want check my array value with in_array my arrays this is:
I use this code but it's not work
if(in_array(167, $array) AND in_array(556, $array) ) {
echo 'ok';
return;
}
now how can check my values?
I want check my array value with in_array my arrays this is:
I use this code but it's not work
if(in_array(167, $array) AND in_array(556, $array) ) {
echo 'ok';
return;
}
now how can check my values?
in_array()
does not work for multi-dimensional arrays , you either have to loop it and do the in_array()
check or merge the array into a single one and then do single in_array()
check.
foreach($array as $k=>$arr)
{
if(in_array(167,$arr))
{
echo "Found";
}
}
$merged_arr = call_user_func_array('array_merge', $array);
if(in_array(167,$merged_arr))
{
echo "Found";
}
EDIT :
<?php
$array = array(array(167),array(167),array(556));
$merged_arr = call_user_func_array('array_merge', $array);
$needle_array = array(167,556,223);
foreach($needle_array as $v)
{
if(in_array($v,$merged_arr))
{
echo "Found";
}
}
You can even use array_intersect()
on these two arrays to get the matched content , if that is what you are looking for.
You could create a mult-dimensional in_array function:
function inArrayMulti($needle, $haystack, $strict=false) {
foreach( $haystack as $item ) {
if( is_array($item) ) return inArrayMulti($needle, $item);
else {
if( $strict && $needle === $item) ) return true;
else if( $needle == $item ) return true;
}
}
return false;
}
May be useful this
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Or
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
echo (isset($lookup_array[152]))?'yes':'no';
Loop through the array
<?php
foreach($array as $ar){
if(in_array(167,$ar) && in_array(556,$ar)){
echo "ok";
}
}
?>
Why all answers use in_array and other difficult construction? We need found only two numbers, easy way for this:
$array = array(array(165), array(167),array(167),array(556));
foreach($array as $key){
foreach($key as $next){
echo 167 == $next || 556 == $next ? '<p>Found<p></br>' : '';
}
}