0

I'm new in php and having problem with a piece of my code if the key given exist. The code of error are below and i don't have a idea what is causing it. Please help.

"Warning: array_key_exists() expects parameter 2 to be array, boolean given in"

The line

if ( is_array(array_key_exists('sizes',wp_get_attachment_metadata($attach_id)) == false ){}
2
  • wp_get_attachment_metadata($attach_id) is returning a boolean instead of an array. Usually meaning the metadata for those attachments weren't found. Commented Jan 28, 2016 at 0:43
  • 1
    Not answering your question but: is_array(array_key_exists(... does not make much sense. array_key_exists returns an bool, and is_array expects an array ... Commented Jan 28, 2016 at 1:02

2 Answers 2

1

As ArSeN already pointed out, is_array(array_key_exists( doesn't make much sense. I guess you were trying: a) is not array or b) lacks a specific key.
Using a temporary variable you can do something like

if ( !is_array($meta=wp_get_attachment_metadata($attach_id)) || !array_key_exists('sizes', $meta) ) {
    // ....
}

Or, in case you try to access the meta data more often (or simply as a coding style):

$meta=wp_get_attachment_metadata($attach_id);
if ( !is_array($meta) || !array_key_exists('sizes', $meta) ) {
    // ....
}
Sign up to request clarification or add additional context in comments.

2 Comments

Simply making the code cleaner makes it much easier to debug.+1
btw: the if condition could be reduced to if ( !isset($meta['sizes']) ) ... since php doesn't complain (not a warning, not a notice) when $meta is false. Not my style, but possible....
0

You could drop a ternary into that thing to uglify the hell out of it.

if ( is_array(array_key_exists('sizes',wp_get_attachment_metadata($attach_id)) == false) ?: array() ){}

This way if the attachment metadata does not exist, it will provide an empty array, which in turn will produce a false from array_key_exists, which is similar to the behave of the desired code.

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.