php.net |  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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: davide dot spagnoli at adam-italia dot it
New email:
PHP Version: OS:

 

 [2018-09-24 15:49 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-09-24 16:09 UTC] 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 16:12 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2018-09-24 16:12 UTC] 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-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-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 12 13:01:33 2025 UTC