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\"
if your array like this
$array = array(
array("name" => "Robert", "Age" => "22", "Place" => "TN"),
array("name" => "Henry", "Age" => "21", "Place" => "TVL")
);
Use this
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
example : echo in_multiarray("22", $array,"Age");
This will work too.
function in_array_r($item , $array){
return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}
Usage:
if(in_array_r($item , $array)){
// found!
}
I believe you can just use array_key_exists nowadays:
<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
This will do it:
foreach($b as $value)
{
if(in_array("Irix", $value, true))
{
echo "Got Irix";
}
}
in_array
only operates on a one dimensional array, so you need to loop over each sub array and run in_array
on each.
As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.
I used this method works for any number of nested and not require hacking
<?php
$blogCategories = [
'programing' => [
'golang',
'php',
'ruby',
'functional' => [
'Erlang',
'Haskell'
]
],
'bd' => [
'mysql',
'sqlite'
]
];
$it = new RecursiveArrayIterator($blogCategories);
foreach (new RecursiveIteratorIterator($it) as $t) {
$found = $t == 'Haskell';
if ($found) {
break;
}
}
I found really small simple solution:
If your array is :
Array
(
[details] => Array
(
[name] => Dhruv
[salary] => 5000
)
[score] => Array
(
[ssc] => 70
[diploma] => 90
[degree] => 70
)
)
then the code will be like:
if(in_array("5000",$array['details'])){
echo "yes found.";
}
else {
echo "no not found";
}