Ethan Jinks O'Sullivan Ethan Jinks O'Sullivan - 3 months ago 12
PHP Question

PHP: array with empty value gives error in foreach

For this example, when I call the variable

$my_settings
, the output would look like this:

Array (
[personal_options] => Array (
[rich_editing] => rich_editing
[admin_color] => admin_color
[comment_shortcuts] => comment_shortcuts
[admin_bar_front] => admin_bar_front
)
[name] => Array (
[nickname] => nickname
)
[contact_info] => Array (
[url] => url
)
[about_yourself] => Array (
[description] => description
)
[yoast_seo] =>
)


When I run a
foreach
loop, get everyone's favorite "Invalid argument supplied for foreach()" error because this array has
[yoast_seo] =>
, which is empty and throwing it off.

Currently my
foreach
is set up as the following:

$my_settings = get_option( 'dsbl_profile_settings' );

if ( is_array( $my_settings ) || is_object( $my_settings ) ) {
foreach ( $my_settings as $group => $item ) {
foreach ( $item as $value ) {
echo '<pre>'; print_r( $value ); echo '</pre>';
}
}
}


As you can see, I already use the
is_array()
and
is_object()
check in my loop. My guess is that I need to also perform a check to see if it's empty as well before it runs
[yoast_seo] =>
? I'm at a loss on the best way to implement that since I've tried the following in my
if
statement:

if ( is_array( $profile_fields ) || is_object( $profile_fields ) || isset( $profile_fields ) ) { // Attempt #1

if ( ( is_array( $profile_fields ) || is_object( $profile_fields ) ) && isset( $profile_fields ) ) { // Attempt #2

Answer

It's because you have nested foreach and you are providing an empty variable, you should check if the variable is array before passing.

if ( is_array( $my_settings ) || is_object( $my_settings ) ) {
    foreach ( $my_settings as $group => $item ) {
        if(is_array($item)) {
            foreach ( $item as $value ) {
                echo '<pre>'; print_r( $value ); echo '</pre>';
            }
        }
    }
}