Reputation: 5172
I have this dynamic array, generate after a submit $_POST.
Array
(
[0] => Array
(
[0] => lng_criteria_balance
[1] => Array
(
[0] => lng_type_balance_positive
)
)
[1] => Array
(
[0] => lng_criteria_sex
[1] => Array
(
[0] => F
)
)
[2] => Array
(
[0] => lng_criteria_note
[1] => Array
(
[0] => cane
)
)
)
Array is variable, and it's key also. I need to search if a specified value exists. I did try this but
<?php
if (in_array('lng_criteria_balance', $args))
{
echo 'found!';
}
else
{
echo 'not found :(';
}
But it prints "not found". Thank you.
PS I could check with a foreach loop, but I would not use it (for best performance)
Upvotes: 2
Views: 73
Reputation: 13665
function multi_in_array_r($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && multi_in_array_r($needle, $element))
return true;
}
return false;
}
Upvotes: 1
Reputation: 5444
Try this...
<?php
$arr = array(0 => array("id"=>1,"temp"=>"lng_criteria_balance"),
1 => array("id"=>2,"temp"=>"test"),
2 => array("id"=>3,"temp"=>"test123")
);
function search_in_array($srchvalue, $array)
{
if (is_array($array) && count($array) > 0)
{
$foundkey = array_search($srchvalue, $array);
if ($foundkey === FALSE)
{
foreach ($array as $key => $value)
{
if (is_array($value) && count($value) > 0)
{
$foundkey = search_in_array($srchvalue, $value);
if ($foundkey != FALSE)
return $foundkey;
}
}
}
else
return $foundkey;
}
}
if(!empty(search_in_array('lng_criteria_balance',$arr)))
{
echo 'found!';
}
else
{
echo 'not found :(';
}
?>
Upvotes: 1
Reputation: 12391
Yes, because in your array, there are numeric keys only. Use foreach to iterate through the subarrays, and search in that.
$inArray = false;
foreach ($array as $key => $subarray) {
if (in_array('needle', $subarray)) {
$inArray = true;
break;
}
}
Upvotes: 1
Reputation: 3425
For multi-dimension array you need to check it recursively.
Do like this:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Output:
echo in_array_r("lng_criteria_balance", $your_array_variable) ? 'found' : 'not found';
Upvotes: 3