0

I don't understand for loop in PHP,

`$total = 0;

for ($i = 1; $i <= 10; $i++) {
    $total += $i;
    
}
echo $total;`

normally equal an 11 no ? he output me 55, but for python when you execute similar code with "while loop"

total = 0

while total <= 10:
    total+=1
print(total)

output me 11

please someone can help me?

3 Answers 3

2

Your PHP and python code is not equivalent. In python you just add 1 each time in the loop. However in the PHP you are adding the value to the $i value, which of course keeps increasing every time - i.e. 1+2+3+3+5...etc.

You could write

$total += 1;

or just

$total++;

instead and it would work the same as the python. But then again that makes $total redundant because it just has the same value as $i, and you don't really need two variables doing the same job.

Or you could write a while loop to be more directly equivalent to the python:

$total = 0;

while ($total <=10) {
  $total++;
}

echo $total;
Sign up to request clarification or add additional context in comments.

Comments

1

PHP CODE

In the PHP code, you get the sum of 1 to 10 numbers using for loop. That is, 0+1+2+3+4+5+6+7+8+9+10 = 55

Because you have initially given 0 to the $total variable in the PHP code. Then you have given 1 to the $i variable in the for loop and you keep increasing the loop 1 by 1 until the value in $i is less than 10 or equal 10. Then the value in $i is added to the value in the $total.

1st Iteration $total = total + 1

2nd Iteration $total = total + 2

3rd Iteration $total = total + 3

. . . . .

10th Iteration(because $i <= 10) $total = total + 10

Then exit the loop and now $total = 55

PYTHON CODE

In the python code you have also using while loop and 0 is assigned to the total variable at the beginning of the code.

In this case all you have to do is increase the value of the total variable by 1

That is,

1st Iteration total = total + 1

2nd Iteration total = total + 1

3rd Iteration total = total + 1

. . . . .

10th Iteration(because total <= 10) total = total + 1

Then exit the while loop and now total = 11

These two codes are not the same!!!

Comments

0

Simply because in php code you are incrementing it with i as:total+i if total wore intially zero 0+1+2+3+4+5+6+7+8+9+10==55 while in python you are incrementing it with total+1 not i so each time only +1 incrementaion so 0+1+1+1+1+1+1+1+1+1+1=11

1 Comment

if you want similar thing in your php script just replace i with1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.