Avatar of Ridgejp
Ridgejp
Flag for United Kingdom of Great Britain and Northern Ireland asked on

PHP - For Loop Question

Hi'

Just researching how 'For loops' behave and I wrote the following ...
<?php

$t = 0;
    
    for($i=1, $j=1; $i<=3, $j>=-3; $i++, $j--)
        
    {
        
        $t = $i * $j;
        echo "$i x $j = $t<br>";
    
    }
?>

Open in new window


I thought I'd get the following results: -

1 * 1 = 1
2 * 0 = 0
3 * -1 = -3

And yet the following happens: -

1 * 1 = 1
2 * 0 = 0
3 * -1 = -3
4 * -2 = -8
5 * -3 = -15

Why doesn't the for loop stop when the first statement for $i hits 3? Equally, if I change $i to <=12 the loop is affected by $j being a negative int and doesn't go below -3.

Hope that makes sense?
J
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
pritaeas

According to the manual:

http://php.net/manual/en/control-structures.for.php

"Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part."

So basically that would mean your code will run while $j>=-3
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Ray Paseur

Footnote: I'm a fairly experienced programmer, and I've never seen anyone do anything quite like what you've posted with this question.  If it's purely academic, I understand.  But if it's going to be part of a deployed application, you might want to post a new question here, and ask about best practices to solve the problem!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23