开发者

In array returning the wrong result

开发者_StackOverflow中文版

I have the below array..

<?php $arrLayout = array(
    "section1" => array(
        "wComingEpisodes" => array(
            "title" => "Coming Episodes",
            "display" => ""
        )
    )); 
?>

Then I want to check if wComingEpisodes is in the array so..

<?php if (in_array( "wComingEpisodes" , $arrLayout )) {
echo "CHECKED";}
?>

However its returning nothing even though it is in the array. Do I need to do something different because of the multiple arrays or where is my mistake?


in_array tests for values, not keys. It also does not test nested values.

$arrLayout = array(
"section1" => array(
    "wComingEpisodes" => array(
        "title" => "Coming Episodes",
        "display" => ""
    )
)); 

echo array_key_exists( 
   "wComingEpisodes",
   // this is the array you're actually looking for
   $arrLayout['section1'] )?'exists':'does not exist'; 


you're getting the correct result according to the documentation.

if you want to search an multidimensional array recursive, take a look at the user contributed notes, where you can find examples like this, that show how to do a recursive search (which seems to be what you're looking for).

EDIT:
i just noticed you're trying to find out if a specific key exists: in this case, you'll have to use array_key_exists (like in_array, this also doesn't do a recursive search, so you'll have to do something like this).


in array searches array values.

the string, "wComingEpisodes", is the key of the value

you may want to try using array_key_exists()


In_array isn't recursive by nature so it will only compare the value you give it with the first level of array items of the array you give it.

Thankfully you're not the first with the problem so heres a function that should help you out. Taken from php.net in_array documentation

function in_arrayr($needle, $haystack) { 
        foreach ($haystack as $v) { 
                if ($needle == $v) return true; 
                elseif (is_array($v)) return in_arrayr($needle, $v); 
        } 
        return false; 
} 

http://www.php.net/manual/en/function.in-array.php#60696

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜