user3325919
user3325919

Reputation: 45

remove last character after concatenating string output by for loop?

$holder = '';

foreach($fields as $key){
    $holder .= $key.', ';
}

echo $holder;

I have the code above, it outputs "a, b, c, " I want to remove the comma after c. I tried substr and it is not working. any help?

Upvotes: 0

Views: 627

Answers (3)

Rimble
Rimble

Reputation: 893

You can use implode() to join all array elements together :

<?php
   $holder = implode(', ', $fields);
   echo $holder;
?>

Upvotes: 3

SRC
SRC

Reputation: 76

You can use substr like this

$holder = '';

foreach($fields as $key){
    $holder .= $key.', ';
}
$newholder=substr($holder, 0, -1); 
echo $newholder;

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

That's not how it's done.

$holder = join(', ', $fields)

Upvotes: 5

Related Questions