php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74871 if statement behavior
Submitted: 2017-07-06 23:51 UTC Modified: 2017-07-07 00:04 UTC
From: johovich at yande dot ru Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.1.7 OS: Linux version 2.6.32-531.23.3.lv
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: johovich at yande dot ru
New email:
PHP Version: OS:

 

 [2017-07-06 23:51 UTC] johovich at yande dot ru
Description:
------------
If i use set var inside 'if' statement condition $var = '0' is the same as $var = false. But it is not the same. So if assign var to function that returns 0 as integer or 0 as string 'if' statement condition works as false.


Test script:
---------------
//In this script you can see, that set var value to 0 is equal to boolean false 
//applied to if statement. There is no diff between integer 0 or string '0'


if($pos = 0){
	$pos++;
} else {
	$pos = 0;
}
var_dump($pos);

//$pos is not boolean false, so it should do if condition true, but it's not

//to make this work well i use this
$pos = 0;
if($pos !== false){
	$pos++;
} else {
	$pos = 0;
}
var_dump($pos);


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-07-07 00:01 UTC] rtheunissen@php.net
This is not a bug. `if ($condition)` is the same as `if ($condition == true)`, so in the second part of your test script if you changed the strict `!==` to `!=`, you would get the same results. 

So you're effectively saying `if (($pos = 0) == true)` which will drop to the `else`.
 [2017-07-07 00:04 UTC] rtheunissen@php.net
-Status: Open +Status: Not a bug
 [2017-07-07 00:04 UTC] rtheunissen@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

This is expected behaviour, an if statement defaults to a non-strict boolean comparison.
 [2017-07-07 08:52 UTC] spam2 at rhsoft dot net
and "if($pos = 0)" is always true because = assigns a value while == and === compare a value

[harry@srv-rhsoft:/downloads]$ php test.php
DO NOT USE A SINGLE = TO COMPARE SOMETHING
[harry@srv-rhsoft:/downloads]$ cat test.php
<?php
if($test = 1)
{
 echo "DO NOT USE A SINGLE = TO COMPARE SOMETHING\n";
}
?>
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 12 09:01:33 2025 UTC