user5603796
user5603796

Reputation: 389

PHP add comma and space unless end of foreach

I am using this code

<?php
foreach($rows as $row) {
echo "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>, ";
}
?>

The problem is that the comma and space (,<space>) are added to even the last $row. What is the simplest method to prevent this? I had an idea to check the size of the array etc. but not sure if this would be over complicating it.

Upvotes: 2

Views: 765

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94672

There is a simpler solution

<?php
$htm = '';
foreach($rows as $row) {
    $htm .= "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>, ";
}
rtrim($htm,', ');
echo $htm;
?>

If you want to get complicated then you could do :-

<?php
$crows = count($rows) - 1;
foreach($rows as $i => $row) {
    echo "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>";
    echo ( $crows > $i ) ? ', ' : '';
}
?>

Upvotes: 4

Sougata Bose
Sougata Bose

Reputation: 31749

You can do this -

<?php
$links= array();
foreach($rows as $row) {
    $links[]= "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>";
}

echo implode(', ', $links);
?>

Or

<?php
$i = 0;
$total = count($rows);
foreach($rows as $row) {
    echo "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>";
    $i++;
    if($i < $total)
       echo ",";
}
?>

Or RiggsFolly's answer is another option.

Upvotes: 5

Pupil
Pupil

Reputation: 23958

You can do it with strings with two ways:

1) Use rtrim()

<?php
$str = '';
foreach($rows as $row) {
$str .= "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>, ";
}
echo rtrim($str, ', ');
?>

2) Take an array of links and implode() by space and comma.

<?php
$arr = array();
foreach($rows as $row) {
$arr[] =  "<a href=index.html?id=" . $row['id'] . ">" . $row['name'] . "</a>, ";
}
echo implode(', ', $arr);
?>

Upvotes: 1

Related Questions