shahzad ahmed shahzad ahmed - 5 months ago 11
PHP Question

Sum Numbers with using for loop in PHP

I want to sum numbers using for loop in PHP.

like:

'1+2+3+4+5+6+7+8+9+10=?'


this will be done using

<?php

$start = 1;
$end = 10;

$sum = 0;
for ($i = $start; $i <= $end; $i++) {
$sum += $i;
}

echo "Sum from " . $start . " to " . $end . " = " . $sum;
?>


The output is: -Sum from 1 to 10 = 55.

But I want to output like this:

1+2+3+4+5+6+7+8+9+10=55

How can I achieve this?

Answer

You need a string variable to keep each value, like so:

$start = 1;
$end = 10;

$text = ''; // added
$sum = 0;

for($i = $start; $i <= $end; $i++){
    $text .= $i==$start ? $i : '+' . $i;  // added
    $sum += $i;
}

echo $text . ' = ' . $sum;

Output:

1+2+3+4+5+6+7+8+9+10 = 55

Comments