1

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

6 Answers 6

2

Use the function array_key_exists.

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

Sign up to request clarification or add additional context in comments.

Comments

1

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()

1 Comment

From example #2 on the PHP array_key_exists page: "isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does." php.net/manual/en/function.array-key-exists.php
1

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'])){
...
}

1 Comment

If that's the case ($arr['logo'] = ''), you should use empty() to check if $arr['logo'] is set to a non-null value.
0

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

Comments

0

You can use array_key_exists.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.