php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75114 anomaly when assigning a var in an if-statement
Submitted: 2017-08-24 13:00 UTC Modified: 2017-08-24 21:46 UTC
From: php at hitchhikers11 dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
 [2017-08-24 13:00 UTC] php at hitchhikers11 dot com
Description:
------------
There is a strange behaveour, 
when assigning a value in an if-statement (=), 
instead of equate the variable with a value (==):

the value of the variable becomes TRUE respectively 1,
this happens only if there is another condition in the 
if-statement after assigning the variable.

Tested with PHP Version 5.6 and 7.?  

Test script:
---------------
$var = "original value";
$var2 = 'some_value';

echo "1: ".$var."<br>";
if($var="value" || false){ echo "2: ".$var."<br>"; }  /* && or || */
if("any_true_value"==$var){echo "3: ".$var."<br>";}

Expected result:
----------------
1: original value
2: value


Actual result:
--------------
1: original value
2: 1
3: 1

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-08-24 17:31 UTC] kalle@php.net
-Type: Security +Type: Bug -Package: *General Issues +Package: Scripting Engine problem
 [2017-08-24 17:38 UTC] kalle@php.net
-Status: Open +Status: Not a bug
 [2017-08-24 17:38 UTC] kalle@php.net
This is because the if conditional is evaluated as:

$var = "value" || false;

meaning that $var is now a boolean, as (bool)"value" === true, therefore causing "1" to be printed when echoing the string.

What you need to do is to set the priority of evaluation like:

($var = 'value') || false

This will yield your desired behavior
 [2017-08-24 18:06 UTC] php at hitchhikers11 dot com
Got it, thanks!
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 11:01:27 2024 UTC