Search code examples
phparrayswordpressimplode

Join 2 echoes and separate with coma - implode, array


I've got 2 variables. First is coming from the taxonomy and outputs the taxonomy term and the second outputs the custom field:

$address_city = get_custom_field( 'address_city' );
        echo '<span>' . $address_city . '</span>';

$terms = get_the_terms($post->id, 'listing_country');
    foreach ( $terms as $term ) {
        echo '<span>' . $term->name . '</span>';
}

The result of this looks like this: CityCountry

I'm trying to figure out how to separate these two echos with a single coma ,, so the result is as follows: City, Country

I've been trying to play around with the implode() and array() , but I just can't figure out how to get this done without errors.


Solution

  • $address_city = get_custom_field( 'address_city' );
            $arr[0] = '<span>' . $address_city . '</span>';
    
    $terms = get_the_terms($post->id, 'listing_country');
        foreach ( $terms as $term ) {
            $arr[1] = '<span>' . $term->name . '</span>';
    }    
        echo implode(", ", $arr);
    

    try this code it will help you for sure..