0

Am having a foreach loop using php and separating the next item with / i would like the / to be removed in the last item

This is the code:

<?php
            $contacts = TblContact::find()->orderBy("id")->all();
            foreach ($contacts as $contact){
                echo $contact->contact."/";   //...  this has the separator /
            }
            ?>

currently it generates:

2362/2332/3332/

I would like it to generate

2362/2332/3332    ... this has no trailing /
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 2
    you can use a condition in your foreach loop to get the last index (and so remove the last "/" : http://stackoverflow.com/a/1070256/6028607 – Vincent G Nov 14 '16 at 08:25

2 Answers2

1
<?php
    $contacts = TblContact::find()->orderBy("id")->all();
    $contactList = [];
     foreach ($contacts as $contact){
        $contactList[] = $contact->contact;
     }
    echo implode("/", $contactList)
?>

try this

Semi-Friends
  • 480
  • 5
  • 17
1

You can use pluck and implode:

$contacts = TblContact::find()->orderBy("id")->pluck('contact')->all();

echo implode('/', $contacts);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50