0

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 . ", "; } ?>

5 Answers 5

2

If

$files->tags->fileTag

is an array, then you can use

$str = implode(', ', $files->tags->fileTag);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. It turned out this is the best solution for me. :)
2
implode(", ", $files->tags->fileTag);

Comments

1

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;
     }
?>

1 Comment

Thanks, this looks very good too. I forgot to mention that my input is an xml string so the $index wouldnt work I guess.
0
<?php
echo implode(",",$files->tag->fileTag);
?>

1 Comment

feel free to validate answer then
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.