2

I'm wondering if there is a more elegant way to do this:

$foo = (isset($bar) and array_key_exists('meh', $bar)) ? $bar['meh'] : '';

If I remove the isset part, PHP issues a warning if $bar isn't an array, if I remove the array_key_exists part, PHP issues a warning if the meh key isn't in the array. Is there a more graceful, warning free, way of achieving the same end?

1
  • I do the same... but have it as a function... oh and a default value (might not always want empty string... might want 0, or null, or empty object etc etc). Commented Jun 26, 2012 at 14:25

2 Answers 2

2

You take exactly the steps required to "secure" code against the warnings you mention.

However, the warnings are there for a reason. Typically it makes more sense to check, if you can prevent situations where the variables you are trying to access are not initialized.

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

2 Comments

+1 for suggesting you know your data. This does not really answer the question but the suggestion itself is very valuable. The PHP community often embraces defensive programming (where you try to handle or hide all errors), but it is often much easier to debug offensive programs which fails on invalid inputs.
Point taken. Initialize the variable as opposed to suppressing the error.
2

You can reference the key directly. Inside isset it won't even throw an exception if $bar is undefined.

$foo = isset($bar['meh']) ? $bar['meh'] : '';

The difference between array_key_exists and isset is that isset will return FALSE if the key corresponds to a NULL value. In my code above, a NULL value will therefore result in $foo begin the empty string, not NULL. If that is a problem your current approach will be the best.

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.