Geoff
Geoff

Reputation: 6649

Removing the last trailing separator in foreach in php

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 /

Upvotes: 0

Views: 108

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You can use pluck and implode:

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

echo implode('/', $contacts);

Upvotes: 1

Semi-Friends
Semi-Friends

Reputation: 480

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

try this

Upvotes: 1

Related Questions