List with commas in PHP and MySql

3

In a page of PHP I have a query of MySQL simple. The final result is a list.

The part that generates the result

while($row = mysqli_fetch_array($result)) {
echo "<a href='".$row['url']."'>".$row['Name']."</a>, ";
}

This generates something like this:

Abc123, Def456, Ghi789,

But I do not want that last comma:

Abc123, Def456, Ghi789

How can I alter the PHP to achieve this?

    
asked by CalvT 26.04.2016 в 15:44
source

2 answers

2

A possible solution would be to save the results in a string and before writing it on the screen using echo , delete the last comma using rtrim or trim (because you can pass them a mask specifying the string ","):

$resultado = "";
while($row = mysqli_fetch_array($result)) {
    $resultado .= "<a href='".$row['url']."'>".$row['Name']."</a>, ";
}
echo rtrim($resultado, ", ");

Another possible solution would be to save the text (without the comma) in an array and then do a implode joining with the comma:

$cadenas = array();
while($row = mysqli_fetch_array($result)) {
    array_push($cadenas, "<a href='".$row['url']."'>".$row['Name']."</a>");
}
echo implode(", ", $cadenas);
    
answered by 26.04.2016 / 15:57
source
0

You can use PHP's substr() function:

$myString = substr($myString, 0, -1);

It will remove the last character from the chain.

    
answered by 26.04.2016 в 17:32