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
}
}
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.
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
}
}
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.