Adding "and" between the last two database results in a 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 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 repeat "and" instead of a comma. But if I have 3 or more results, it will say "result and result, result and result". I want him to say "result, result, result and result."
Any ideas?
Try the following idea
if (count($solos) > 2) {
$last = array_pop($solos);
echo implode(', ', $solos) . ' and ' . $last;
}
else
{
echo implode(' and ', $solos);
}
you can read it, and in the second add id and "instead of", "
$x = count($solos);
foreach($solos as $solo){
echo $solo->id;
if ($solos[$x - 2] == $solo){
echo 'and';
}elseif ($solos[$x -1] != $solo && $solos[0] != $solo){
echo ','
}
}
I would rather use for
instead 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 ", ";
}
}
}
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++;
}
The other answers work fine. For completeness, you can also insert "and" using preg_replace.
$solos = array( 'one', 'two', 'three', 'four' );
$result = implode(', ',$solos);
$result = preg_replace('/, ([^,]+)$/',', and \1', $result);
Over 1 million iterations, mnv's array_pop method took 2.13 seconds. preg_replace completed in 3.65 seconds. Using array_pop would be preferable.