Search code examples
phpadvanced-custom-fields

ACF Fields - Array Loop - IF Statement


I am using this code that returns an array:

$values = get_field('sp_specialism', $prev_id);var_dump($values);

The output of the array is:

array(3) { [0]=> string(4) "Asia" [1]=> string(6) "Canada" [2]=> string(9) "Caribbean" } 

I am trying to loop through the array and output Asia Canada Caribbean as list items

if($values) { echo '<ul>'; foreach($values as $value) { echo '<li>' . $value . '</li>'; } echo '</ul>'; } 

However my if statement is erroring out. Not sure why this happens.

I am using this within another piece of code like this:

$string = "<span class=\"bkcards-exp\">" . get_field('sp_location', $prev_id) . "</span><span class=\"bkcards-left\">" . if($values) { echo '<ul>'; foreach($values as $value) { echo '<li>' . $value . '</li>'; } echo '</ul>'; } . "</span>" 

Solution

  • You can't concatenate an if statement with a string. Instead, you can divide the string into multiple different statements as shown in the following snippet.

    $string = '<span class="bkcards-exp">' . 
                   get_field('sp_location', $prev_id) . 
              '</span><span class="bkcards-left">';
    
    if($values) { 
        $string .= '<ul>'; 
        foreach($values as $value) { 
            $string .= '<li>' . $value . '</li>'; 
        } 
        $string .= '</ul>';
    }
    
    $string .= '</span>';