php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #27409 Comparison order of operations incorrect
Submitted: 2004-02-26 19:29 UTC Modified: 2004-02-26 19:45 UTC
From: keithm at aoeex dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5CVS-2004-02-26 (dev) OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: keithm at aoeex dot com
New email:
PHP Version: OS:

 

 [2004-02-26 19:29 UTC] keithm at aoeex dot com
Description:
------------
The order of operation for comparisons seems to be incorrect.  The following example script will demonstrate the problem:

Reproduce code:
---------------
<?php

$x=0; 

while ($x != ($x=5)){
   echo "x is not equal to x";
}
?>


Expected result:
----------------
The screen should display nothing.

I would expect that the $x=5 would execute, and then php would compare $x != $x, which of course would be false, and the loop would run.



Actual result:
--------------
x is not equal to x

the loop is executed and that echo statement is displayed.

It seems that php pulls the value of $x, execute the $x=5 statement, and runs the comparison.  So for a split second, you in essence have two $x variables.  One which has the value of 0, and the other with the value of 5.

If you reverse the order of the operands in the condition, then it works as expected:


<?php

$x=0; 

//This works fine, nothing is displayed
while (($x=5) != $x){
   echo "x is not equal to x";
}
?>


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-02-26 19:45 UTC] abies@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

The engine evaluates the operands in the order they occur in the input, as there is no reason to evaluate the second expression first. [The parentheses don\'t change that.] The first expression evaluates to 0, the second one to 5.
 [2010-06-09 19:19 UTC] ndsharp at gmail dot com
I agree that this is incorrect. When preforming computations in a comparison statement everything in the parentheses should be evaluated before the comparison is made. 

doing:
    for($i=0; $i < ($arr - 8);$i++)
    {
    }
will have $i compared to $arr but not the value of ($arr - 8). That is wrong.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jun 01 19:01:30 2024 UTC