Ethan Rævan
Ethan Rævan

Reputation: 333

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

Upvotes: 1

Views: 4076

Answers (2)

masterFly
masterFly

Reputation: 1112

You have checked is_array( $my_settings ) for $my_settings, which is correct. But what about foreach ( $item as $value )?

Your error is there for the group level loop. Not for $my_settings.

So if you do

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

it should work. Basically same condition that you are checking for $my_settings.

Hope this helps you!

Upvotes: 1

kamal pal
kamal pal

Reputation: 4207

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>';
            }
        }
    }
}

Upvotes: 1

Related Questions