I use in_array()
to check whether a value exists in an array like below,
$a = array(\"Mac\", \"NT\", \"Irix\", \"Linux\");
if (in_array(\"Irix\"
Please try:
in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])
Im not sure about the need, but this might work for your requirement
Shorter version, for multidimensional arrays created based on database result sets.
function in_array_r($array, $field, $find){
foreach($array as $item){
if($item[$field] == $find) return true;
}
return false;
}
$is_found = in_array_r($os_list, 'os_version', 'XP');
Will return if the $os_list array contains 'XP' in the os_version field.
For Multidimensional Children: in_array('needle', array_column($arr, 'key'))
For One Dimensional Children: in_array('needle', call_user_func_array('array_merge', $arr))
If you know which column to search against, you can use array_search() and array_column():
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
This idea is in the comments section for array_search() on the PHP manual;
It works too creating first a new unidimensional Array from the original one.
$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");
foreach ($arr as $row) $vector[] = $row['key1'];
in_array($needle,$vector);
Since PHP 5.6 there is a better and cleaner solution for the original answer :
With a multidimensional array like this :
$a = array(array("Mac", "NT"), array("Irix", "Linux"))
We can use the splat operator :
return in_array("Irix", array_merge(...$a), true)
If you have string keys like this :
$a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux"))
You will have to use array_values
in order to avoid the error Cannot unpack array with string keys
:
return in_array("Irix", array_merge(...array_values($a)), true)