|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76927 Assignments in "if" conditions
Submitted: 2018-09-24 15:49 UTC Modified: 2018-09-25 08:34 UTC
From: davide dot spagnoli at adam-italia dot it Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.1.22 OS: CentOS Linux release 7.5.1804 (C
Private report: No CVE-ID: None
 [2018-09-24 15:49 UTC] davide dot spagnoli at adam-italia dot it
In a set of conditions evaluated by an "if" block, an assignment is not recognized by next conditions.

Test script:
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


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-09-24 16:09 UTC] spam2 at rhsoft dot net

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 16:12 UTC]
-Status: Open +Status: Not a bug
 [2018-09-24 16:12 UTC]
&& has higher precedence than =, see 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-25 08:34 UTC] davide dot spagnoli at adam-italia dot it
@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...
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Mon Jul 22 09:01:25 2019 UTC