Search code examples
phpforeachargumentsflickradvanced-custom-fields

Invalid argument supplied for foreach() when deselecting an Array


The code down below displays an array of flicker images from a plugin that works with Advanced Custom Fields. The problem I have is if I had previously selected a gallery to show but now deselect it I get an error 'Warning: Invalid argument supplied for foreach() in...'

How can I fix this? Obviously if nothing is selected or if something is deselected it shouldn't output anything.

Thanks and this is my first time using stackoverflow so I appreciated any help, please be gentle, I'm very much a novice at php. :)

<?php
$flickr_set = get_field(post_flickr_set);
echo '<div #id="flickr-set" class="flickr-gallery">';
if (isset($flickr_set['items'])) {
    foreach ($flickr_set['items'] as $id => $photos) {
        foreach ($photos as $photo) {
            echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '"><img src="' . $photo['thumb'] . '" /></a>';
        }
    }
echo '</div><!-- end flickr-set -->';
}

?>

Solution

  • You just have to check if the value is also an array like:

    $flickr_set = get_field(post_flickr_set);
    // You can do a var_dump($flickr_set); to see what you are actually getting.
    // Perhaps $flickr_set['items'] == false so it may get set, but not as an array to loop through
    
    echo '<div #id="flickr-set" class="flickr-gallery">';
    
    // The foreach() requires an array, so if $flickr_set['items']
    // is not an array, foreach() will throw an error
    // If this value is an array but is empty, you can use !empty($flickr_set['items'])
    if (isset($flickr_set['items']) && is_array($flickr_set['items'])) {
        foreach ($flickr_set['items'] as $id => $photos) {
            foreach ($photos as $photo) {
                echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '"><img src="' . $photo['thumb'] . '" /></a>';
            }
        }
    echo '</div><!-- end flickr-set -->';
    }