简体   繁体   中英

php if array key exists inside multidimentional array

how can i check if logo exists in this array called $attachements print_r is below:

Array ( [logo] => /home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif )

when theres no logo, the array print_r's

Array ( )

i tried: if (isset($attachments['logo']) ) {..} but the conditional code runs when there is no logo

Use the function array_key_exists .

http://php.net/manual/en/function.array-key-exists.php

It's very stange that isset() is not working, I am pretty sure it should. Maybe you have a problem elsewhere in your code.

Anyway, if you want to try something else, there is a specific function: array_key_exists()

This works for me as expected:

$arr['logo'] = '/home/richar2/public_html/ioagh/images/stories/jreviews/20100510115659_1_img.gif';
print_r($arr);

if (isset($arr['logo'])){
    echo $arr['logo'];
}else{
    echo 'Key doesn\'t exist!';
}

Are you sure you set $arr['logo'] = null, not $arr['logo'] = ''? For the latter you can also check

if (isset($arr['logo'] && !empty($arr['logo'])){
...
}

but the conditional code runs when there is no logo

You could construct an else clause to take appropriate action:

if (isset($attachments['logo']))
{
  // logo is set
}
else
{
  // loto is not set
}

Or simply try this:

if (array_key_exists('logo', $attachments))
{
    // logo is set
}

More info on array_key_exists

您可以使用array_key_exists

you could write it like:

function md_array_key_exists ($key, $array)
{
    foreach ($array as $item => $val)
    {
        if ($item === $key)
        {
            return true;
        }

        if (is_array ($val))
        {
            if (true == marray_key_exists ($key, $val))
                return true;
        }
    }

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM