user1562232
user1562232

Reputation: 1

Why does this PHP code give "undefined index"?

I have this code:

print_r(array_keys($variables));
if (array_key_exists('form', $variables)) {
 print "YES!";
}
$imgs = $variables['form']['field_images'];

It's a part of the code that I use to theme a form page in Drupal. YES is printed out, however, drupal reports undefined index for that. Thanks for your generous help

Upvotes: 0

Views: 253

Answers (3)

Abid Hussain
Abid Hussain

Reputation: 7762

Try this:-

PHP throws the notice. You can add an isset() or !empty() check to avoid the error, like such:

if(isset($variables)) ) && !empty($variables)) ))
{

    if (array_key_exists('form', $variables)) {
     print "YES!";
    }
    $imgs = $variables['form']['field_images'];

}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

as an example implemenation of Ikke`s answer:

if ( !array_key_exists('form', $variables) ) {
    echo 'missing parameter form';
}
else if ( !array_key_exists('field_images', $variables['form']) ) {
        echo 'missing parameter field_images';
}
else {
    $imgs = $variables['form']['field_images'];     
}

Upvotes: 0

Ikke
Ikke

Reputation: 101231

$variables['form'] does exist, but $variables['form']['field_images] probably not. That's why you get the notice about undefined index.

So you should make sure that the subkey also exists before you are calling it.

Upvotes: 1

Related Questions