php – Take all the names and put a comma to separate them

Question:

When I get the names and add them to a variable, I can't separate them with commas normally.

  • it has to be a comma and a period at the end
  • I can't wrap each name in a line break using

It's hard to explain, but here's an example:

while ($listintegrantes = mysqli_fetch_array($query1)) {
        $integrantes = "$integrantes" . $listintegrantes['nome'] . ",";
}

that is, it will show like this:

john, Cyrax, john2,

But I want you to stay:

john, Cyrax and john2.

How is it possible to do this?

-SOLUTION

Below is the resolution of the problem posted above, all the resolutions are correct, I adapted it to my problem so that I return my correct objective.

        $query1 = mysqli_query($conexao, $sql1);
        $integrantes = "";
        $i = mysqli_num_rows($query1);
        $x = 1;
        while ($listintegrantes = mysqli_fetch_array($query1)) {
            $integrantes = $integrantes . $listintegrantes['nome'];
            if ($x < $i - 1) {//antes do penultimo
                $integrantes = $integrantes . ", ";
            }elseif($x == $i-1){//penultimo
                $integrantes = $integrantes . " e ";
            }elseif($x == $i){//ultimo
                $integrantes = $integrantes . ".";
            }
            $x++;
        }

Below is the feedback from the above algorithm: Cyrax, John, Serana and Smigol.

when there is only one member record: Serana.

Answer:

You can do it like this:

$sinal = ", ";
$size = mysqli_num_rows($query1);
$i = 1;
while ($listintegrantes = mysqli_fetch_array($query1)) 
{
    if($i == $size-1) 
        $sinal = " e ";
    elseif($i == $size) 
        $sinal = ".";

    $integrantes .= $listintegrantes['nome'] . $sinal;
    $i++;
}
Scroll to Top