0

I am trying to make a calculator.

How can I make that after the final iteration of the foreach loop the plus symbol in the echo command disappears?
Now it's being displayed as

55 + 22 + 4 + = RESULT

$numbers = array (55, 22 , 4);
        foreach ($numbers as $number) {
            echo "$number + ";
Michel
  • 4,076
  • 4
  • 34
  • 52
Solid Box
  • 3
  • 2
  • Probably, you don't want to echo directly? Removing outputted characters is not possible, or at least not worth the overhead – Nico Haase May 09 '18 at 10:07

4 Answers4

2

Use implode() function instead of foreach:

echo implode(" + ", $numbers);
Tomasz
  • 181
  • 12
0

If you need foreach

$numbers = array (55, 22 , 4);
$i=0;
foreach ($numbers as $number) {
    $i++;
    echo "$number ";
    if(count($numbers) != $i){
        echo "+ ";
    }
}
Yura Rosiak
  • 255
  • 2
  • 13
0

See this post, it has a great answer. For your use case I would suggest the same as Tomasz. But in case you want to know how you can find the last loop I'll leave this here.

$numbers = array(55, 22, 4);
$i = 0;
$len = count($numbers);
foreach ($numbers as $number) {
    if ($i == 0) {
        // first
    } else if ($i == $len - 1) {
        // last
    }

    $i++;
}
Classified
  • 560
  • 1
  • 7
  • 21
0

There is another easy way for that, you don't need to use loops here. Try it with the implode() method.

$numbers = array (55, 22 , 4);
echo implode(' + ', $numbers);