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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 09:01:28 2024 UTC