Ann
Ann

Reputation: 471

How to use implode function in foreach loop

I want to display a ",(comma)" in between each records fetched from the db.eg:location1,location2,location3 etc

<table class="table table-striped table-condensed table-hover">
<?php 
    //var_dump($volunteer_panel_location);
    echo "<tr>"
       . "<td class='col-xs-4'>Interview Location </td>"
       . "<td>";
    foreach ($volunteer_interview_location as $vlocations)
    {
        echo "{$vlocations->location}";
    }
    echo "</td></tr>"
       . "<tr>"
       . "<td>Panel Location </td>"
       . "<td>";
    foreach ($volunteer_panel_location as $plocations)
    {
        echo "{$plocations->location}";
    }
    echo "</td>"
       . "</tr>";
?>
</table>

I tried this,but the records repeated

$pp=array();
foreach ($volunteer_panel_location as $plocations)
{
    $pp[]=$plocations->location;
    echo implode(",",$pp);
}

Upvotes: 1

Views: 2856

Answers (3)

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

try this

echo implode(",",$volunteer_panel_location);

Upvotes: 0

Patel Kishan
Patel Kishan

Reputation: 65

$ar='';   
for ($i=0; $i <count($data) ; $i++) {
    $ar[]=$data[$i]->id;
}
$rt=implode(',',$ar);
echo $rt;

replace $data to your data.

$ar is an array.

I suggest calling implode outside of foreach function.

Upvotes: 1

jmattheis
jmattheis

Reputation: 11125

Try this

$locations = [];
foreach ($volunteer_panel_location as $plocations)
{
    $locations[] = $plocations->location;
}
echo implode(",",$locations);

Upvotes: 1

Related Questions