Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Say I have a data structure like this:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(3) "foo"
  ["message"]=>
  array(1) {
    ["action"]=>
    string(3) "PUT"
  }
}

Where 'message' and 'action' are both optional. To check if they're present my first attempt would be to write something like this:

if (array_key_exists('message', $array) && array_key_exists('action', $array['message'])){
}

Is there a cleaner implementation?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

No, this is just the way of doing it.

Even when I'm not limited to a certain script language, I can't think of an cleaner solution?

share|improve this answer

See also: http://stackoverflow.com/questions/2948948/array-key-exists-is-not-working

You can write an array_key_exists utility function which works recursively.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.