I need to make a loop in php that does 1 + 2 + 3 + 4 .... + 10 = 55 but icant get it to work. I did this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
for ($i = 1; $i <= 10; $i++){
$sul = $i + $i + $i + $i + $i + $i + $i + $i + $i + $i;
echo "$i + $i + $i + $i + $i + $i + $i + $i + $i + $i = $sul<br>";
};
?>
</body>
Hope you can help me thanks :)
This code should help you:
<?php
$sum = 0;
for($i = 1; $i<=10; $i++) {
$sum = $sum + $i;
}
echo $sum;
?>
You are incorrect using loop.
Explanation
I think it will be easier to understand with following table:
_____________________
|JUMP | $i | $sum |
|1 | 1 | 1 |
|2 | 2 | 3 |
|3 | 3 | 6 |
|4 | 4 | 10 |
|5 | 5 | 15 |
|6 | 6 | 21 |
|7 | 7 | 28 |
|8 | 8 | 36 |
|9 | 9 | 45 |
|10 | 10 | 55 |
More about for you can read in PHP: for
Update
If you want your structure it can be as follows:
<?php
$sum = 0;
$str = '';
for($i = 1; $i<=10; $i++) {
$sum = $sum + $i;
$str .= $i == 10 ? $i." = " : $i." + ";
}
echo $str.$sum;
?>
And it will output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Something like this perhaps?
$range = range(1, 10);
$sum = array_sum($range);
echo implode(' + ', $range) . ' = ' . $sum;
range() - http://php.net/range
array_sum() - http://php.net/array_sum
implode() - http://php.net/implode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With