1

I have a foreach loop that does something depending on the contents of an ACF repeater field (map_destinations). It works fine if there are destinations, but if there aren't I get:

"Invalid argument supplied for foreach()"

Here's my code:

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
    foreach ($map_destinations as $map_destination) {
    $map[] = $map_destination['destination'];
}

I have tried various solutions but none work. The most commonly accepted method seems to be:

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
if (is_array($map)) {
    foreach ($map_destinations as $map_destination) {
    $map[] = $map_destination['destination'];
    }
}

Where am I going wrong? Please bear with me, I am just getting to grips with php.

user2265915
  • 539
  • 3
  • 11
  • 22

1 Answers1

2

You should not check for is_array($map)rather check for is_array($map_destinations), or !empty()

$map_destinations = get_field('map_destinations', $tour_id);        
$map = array();
if (is_array($map_destinations)) {
    foreach ($map_destinations as $map_destination) {
        $map[] = $map_destination['destination'];
    }
}
lloiacono
  • 4,714
  • 2
  • 30
  • 46