Bug #76927 [Nab]: Assignments in "if" conditions
| From: | davide dot spagnoli at adam-italia dot it | Date: | Tue, 25 Sep 2018 08:34:25 +0000 |
| Subject: | Bug #76927 [Nab]: Assignments in "if" conditions | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-217231@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=76927&edit=1
ID: 76927
User updated by: davide dot spagnoli at adam-italia dot it
Reported by: davide dot spagnoli at adam-italia dot it
Summary: Assignments in "if" conditions
Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: CentOS Linux release 7.5.1804 (C
PHP Version: 7.1.22
Block user comment: N
Private report: N
New Comment:
@nikic thanks, you're right! I was terribly wrong in simplifying my problem, which still
persists with brackets but involves mysqli_fetch_assoc function, I will submit another bug report
because modifying this one is misleading.
@spam2 further comments are unnecessary...
Previous Comments:
------------------------------------------------------------------------
[2018-09-24 16:12:42] nikic@php.net
&& has higher precedence than =, see http://php.net/manual/en/language.operators.precedence.php.
As such, your code is interpreted as
if ($j = (1 && $j++==1 && $j==2))
rather than
if (($j = 1) && $j++==1 && $j==2)
You can use the latter code to achieve the desired behavior.
@rhsoft: Please avoid words like "nonsense". Especially if you are completely wrong.
------------------------------------------------------------------------
[2018-09-24 16:09:04] spam2 at rhsoft dot net
nonsense!
if($j=1 && $j++==1 && $j==2)
a logical "and" operates from left to right and since $j is undefined and hence not 1
nothing else is evaluated (besides that $j++==1 is a terrible construct)
can you tell one logical reason why anything after && should be evaluated instead stopped
after the first not matching condition?
that's how you optimize for performance: order the cheapest and most likely hitting stuff left
in your && series and the expensive ones like function calls right
------------------------------------------------------------------------
[2018-09-24 15:49:14] davide dot spagnoli at adam-italia dot it
Description:
------------
In a set of conditions evaluated by an "if" block, an assignment is not recognized by next
conditions.
Test script:
---------------
$i=1;
if($i++==1 && $i==2){
echo "I'm in";
}
// output "I'm in"
if($j=1 && $j++==1 && $j==2){
echo "I'm in again";
}
// notice "Undefined variable: j" and no output
Expected result:
----------------
output: "I'm in"
output: "I'm in again"
Actual result:
--------------
output: "I'm in"
notice "Undefined variable: j" and no output
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=76927&edit=1