|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-12-11 23:42 UTC] 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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Dec 16 22:00:01 2025 UTC |
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 { ... }...or I suppose I could always do: <?php if (is_numeric($val_1) && !is_float($val_1)) { ... }This is really what the filter functions are for. if (filter_var($_GET['val_1'], FILTER_VALIDATE_INT)) { ... } or better: if (filter_input(INPUT_GET, 'val_1', FILTER_VALIDATE_INT)) { ... }