user7147407 user7147407 - 17 days ago 5
PHP Question

PHP Loop 1 to 10

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 :)

Answer

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