1

I have an associative array of arrays. The associative array of arrays does not always contain the same sub-arrays. I would like to loop through a particular sub-array if it exists. Is there a more elegant way to do the following code:

if ( array_key_exists( 'fizzy_drinks', $drinks ) ) {

    foreach ( $drinks['fizzy_drinks'] as $fizzy_drink ) {

        // do something with $fizzy_drink
    }
}
1
  • 1
    That's how I would do it. Simple yet effective. This question is better suited to codereview.stackexchange.com though. Commented Jun 4, 2013 at 21:53

4 Answers 4

1

Not really. I think your solution is quite elegant, and readable. I would do:

if (array_key_exists('fizzy_drinks', $drinks) && is_array($drinks['fizzy_drinks'])) {
    foreach ($drinks['fizzy_drinks'] as $fizzy_drink ) {
        // do something with $fizzy_drink
    }
}

Always nice to check if the value you try to use foreach on really is an array.

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

Comments

1

Not really, this is as much elegant as it gets:

if (isset($drinks['fizzy_drinks'])) {
    foreach ( $drinks['fizzy_drinks'] as $fizzy_drink ) {
        // do something with $fizzy_drink
    }
}

If you omit the isset you will get a notice if fizzy_drinks is not set, and a warning if $drinks is not an array.

Comments

1

You might prefer to use is_array:

if(is_array($drinks['fizzy_drinks'])) {
  foreach ($drinks['fizzy_drinks'] as $fizzy_drink) {
    // do something with $fizzy_drink
  }
}

1 Comment

Works but you still get the damn notice thingy if $drinks doesn't have a 'fizzy_drinks' entry
1

You can use:

if (! empty($drinks['fizzy_drinks']) && is_array($drinks['fizzy_drinks'])) {
    foreach ($drinks['fizzy_drinks'] as $fizzy_drink) {
        // do something with $fizzy_drink
    }
}

no warnings, no notices

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.