Take all the names and put comma to separate them

Asked

Viewed 2,967 times

13

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

  • has to be by comma and period at the end
  • I can’t put each name in 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, this will show so:

John, Cyrax, john2,

But I want you to stay:

John, Cyrax and john2.

How is it possible to do this?

-SOLUTION

Follow the resolution of the problem posted above, all resolutions are correct, I adapted to my problem to return me 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++;
        }

follows below the above algorithm feedback: Cyrax, John, Serana and Smigol.

when there is only one member record: Serana.

  • You can iterate the variable members backwards and when you find the comma, switch to . and continue, when the next-to-last comma is found, to be replaced by e.

  • Can use a rtrim($integrantes, ',') at the end of the while and then only concatenate a point at the end. One idea only.

  • I removed the solution from your question, their place is in the answers.

  • 3

    It is better to create an answer with your solution, the question space is only for question :P. The site works different from a forum see the differences in tour is a quick guide :)

  • 1

    Your solution seems to have been adapted based on the @Jorge B.’s response, you can mark his response as correct. Votes do not influence the choice.

  • Yes, thank you, I’m adapting on this site yet, I don’t even know what it’s like to choose the answer yet .... rs, but I’ll see here. I believe it’s green.

  • Just choose the answer that suits your case best, there is no mystery rs. Take a look at the help later to get any questions. And problems can be solved in Meta.

Show 2 more comments

5 answers

10


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++;
}
  • he returned John1, Cyrax, john2,

  • @Murilomanzolicollapse I made a forehead change now

  • returned John1 and Cyrax and John2.

  • I tested it and here it was right. Copy all the code I put here.

  • I will give a lock on the code, then post the solution based on your, very good ! thanks if you want to continue editing, quiet ^^

9

Another way would be to simply remove the last element of the array, use implode to place the commas if there is enough name for the separation and then replace the last element back.

    function names( array $names )
    {
        $_names = array_pop( $names );

        if( count( $names ) > 0 )
        return implode( ', ' , $names ) . ' e ' . $_names;

        return 'só ' . $_names;
    }

    // output: só eu
    echo names( ['eu'] );

    // output: eu e tu
    echo names( ['eu' , 'tu' ] );

    // output: eu, tu e ele
    echo names( ['eu' , 'tu' , 'ele' ] );
  • 1

    +1 didn’t even cross my mind.

  • I’ll take a look, soon put the correct solution, thank you very much !

  • 1

    There is no 'right solution', just look at the many answers... You just need to choose the most adaptable solution to what you need. Any doubt just comment.

7

Another way to do it is to use contrary logic, concatenate the string with e(yes has spaces) and at the end use preg_replace to replace all the e for , except the last one, this control is done with the fourth parameter which is the number of substitutions.

In the example of an array with five elements will become a string with four e, now just know the number of replacements made which is the total of elements minus two which is 3.

Example 1

$itens = 1;
while ($listintegrantes = mysqli_fetch_array($query1)) {
       $integrantes = "$integrantes" . $listintegrantes['nome'] . " e ";
       $itens++;
}

$str = preg_replace('/ e /', ', ', $integrantes, $itens - 2);

Example 2 ideon

$arr = array('john', 'Cyrax', 'john', 'Sonia', 'Sector');
$str = implode(' e ', $arr);
$itens = count($arr);
$str_formatada = preg_replace('/ e /', ', ', $str, count($arr)-2);
echo $str_formatada;

saida : john, Cyrax, john, Sonia e Sector

4

It could be so:

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

$integrantes = rtrim($integrantes, ',') . '.';
  • 3

    is missing the " and " in the penultimate.

  • Great, I didn’t hit that.

4

Another possible solution to get the position of the last occurrence of the character in the string strrpos and replace substr_replace, example:

$arr = array('john', 'Cyrax', 'john', 'Sonia', 'Sector');
$str = implode(', ',$arr);
$str = substr_replace($str, ' e', strrpos($str,','), 1);
echo $str;

Ideone example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.