user2571510
user2571510

Reputation: 11377

PHP: create string with values separated by comma BUT without comma at the end of string

I am using the following PHP snippet to echo data to an HTML page. This works fine so far and returns results like the following example: value1, value2, value3, value4, value5,

How can I prevent it from also adding a comma at the end of the string while keeping the commas between the single values ?

My PHP:

<?php foreach ($files->tags->fileTag as $tag) { echo $tag . ", "; } ?>

Many thanks in advance for any help with this, Tim.

Upvotes: 0

Views: 124

Answers (5)

Daniel
Daniel

Reputation: 1420

implode(", ", $files->tags->fileTag);

Upvotes: 2

stavgian
stavgian

Reputation: 121

A simple way to do this is keep a counter and check for every record the index compared with the total item tags.

<?php 
$total = count($files->tags->fileTag);
foreach ($files->tags->fileTag as $index =>  $tag) { 
   if($index != $total - 1){
        echo $tag.',';
     } else{
        echo $tag;
     }
?>

Upvotes: 1

Jake Gabb
Jake Gabb

Reputation: 385

Assuming you're using an array to iterate through, how about instead of using a foreach loop, you use a regular for loop and put an if statement at the end to check if it's reached the length of the loop and echo $tag on it's own?

Pseudocode off the top of my head:

for($i = 0, $i < $files.length, $i++){
    if ($i < $files.length){
        echo $tag . ", ";
    } else {
        echo $tag;
    }
}

Hope that helps x

Edit: The implode answers defo seem better than this, I'd probably go for those x

Upvotes: 0

dweeves
dweeves

Reputation: 5605

<?php
echo implode(",",$files->tag->fileTag);
?>

Upvotes: 0

Valdas
Valdas

Reputation: 1074

If

$files->tags->fileTag

is an array, then you can use

$str = implode(', ', $files->tags->fileTag);

Upvotes: 2

Related Questions