Bug #71099 [Nab]: Basic assertion failing in PHP 7
| From: | cdtreeks at gmail dot com | Date: | Sat, 12 Dec 2015 00:00:39 +0000 |
| Subject: | Bug #71099 [Nab]: Basic assertion failing in PHP 7 | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-197818@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=71099&edit=1
ID: 71099
User updated by: cdtreeks at gmail dot com
Reported by: cdtreeks at gmail dot com
Summary: Basic assertion failing in PHP 7
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: CentOS 7
PHP Version: 7.0.0
Block user comment: N
Private report: N
New Comment:
Perhaps it would have helped to mention the context here as I'm trying to validate $_POST data.
For example a user submitting a value of 100 in a form. When PHP receives this it'll be a
string.
For strict form validation, I was trying to make sure that int fields were only even processing an
int response.
is_int() can't be used as when being used on a string, you'll get false. Is numeric can
help, but this would also return true for a float.
Seems the best way around it is a bit of a hack:
<?php
<?php
$val_1 = 'test_string'; // Value is 'test_string'
$val_2 = (string) (int) $val_1; // Value is '0' - This MUST be cast back to a string
after typecasting the value to an int
if ($val_1 == $val_2) {
// This now works as expected as we're comparing two strings
} else {
...
}
Previous Comments:
------------------------------------------------------------------------
[2015-12-11 23:51:41] rasmus@php.net
You want === there otherwise you are comparing an int to a string and type coercion is going to make
both sides int. The integer value of your string is 0 so 0 == 0.
------------------------------------------------------------------------
[2015-12-11 23:51:24] nikic@php.net
This is how PHP has always worked, nothing to do with PHP 7.
The "logic" behind it is that an integer to string comparison will cast the string to an
integer, thus giving you the result you observe. I think this is generally agreed to be not very
useful, but also unlikely to change due to BC concerns.
------------------------------------------------------------------------
[2015-12-11 23:42:48] cdtreeks at gmail dot com
Description:
------------
Comparing two different values is failing to assert correctly in the latest release of PHP 7. See
'Test script' below for more details.
Test script:
---------------
<?php
$val_1 = 'test_string'; // Value is 'test_string'
$val_2 = (int) $val_1; // Value is 0
if ($val_1 == $val_2) {
// PHP believes 'test_string' == 0
...
} else {
...
}
Expected result:
----------------
The else clause should be hit.
Actual result:
--------------
The initial condition is returning true
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=71099&edit=1