2

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I do love counting Cows, get me off to sleep in no time. hehehe
@RiggsFolly I do the same too!! You have already seen that.. ;)
everyone likes to count cows... :) bros @RiggsFolly
4

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 ) ? ', ' : '';
}
?>

Comments

1

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

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.