Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Adding "and" between last two database results in foreach loop

I want to add the word "and" between the last two MySQL results. I can add commas but I need to add commas between the first ones and then "and" between the last two.

Here is the code I'm using:

        $not_first = false;

        foreach($solos as $solo)
        {
            if ($not_first)
            {
                echo ', ';
            }
            $not_first = true;

            echo $solo->id;
        }

I could echo 'and' instead of the comma. But if I have 3 or more results it would say "result and result and result and result". I want it to say "result, result, result, and result".

Any ideas?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Try to use next idea

if (count($solos) > 2) {
    $last = array_pop($solos);
    echo implode(', ', $solos) . ' and ' . $last;
}
else
{
    echo implode(' and ', $solos);
}
about 4 years ago · Santiago Trujillo Relatório

0

I'd prefer using for instead of foreach in this case:

for($i=0; $i<count($solos); $i++){
    echo $solos[$i]->id;

    if($i == count($solos) - 2){        // --> second last element, implies "and" 
        echo " and ";
    }
    else{
        if($i != count($solos) - 1){    // --> "," for all other elements, except last
            echo ", ";
        }    
    }
}
about 4 years ago · Santiago Trujillo Relatório

0

Or use this:

   $i = 1;
   $last = count($solos);
    foreach($solos as $solo)
    {
        if ($i > 1 && $i != $last)
        {
            echo ', ';
        }
        elseif ( $i == $last )
        {
            echo ' and ';
        }

        echo $solo->id;
        $i++;
    }
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda