php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #3465 erroneous comparison of intval() return value
Submitted: 2000-02-12 04:51 UTC Modified: 2000-02-13 13:10 UTC
From: zeekamotay at hotmail dot com Assigned:
Status: Closed Package: Other
PHP Version: 3.0.14 OS: Linux 2.2.x
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: zeekamotay at hotmail dot com
New email:
PHP Version: OS:

 

 [2000-02-12 04:51 UTC] zeekamotay at hotmail dot com
I'm trying to tell the difference between a string value and an integer value -- not a string type variable and an integer type variable. I.e., if a string type variable contains the value "503", I want to consider it an integer. So, I use intval(), figuring that if the intval() of a variable is the same as the value of the variable, then the variable has an integer value.

For example, if $x = "503", then intval($x) = 503. So, $x == intval($x) and I consider it an integer. If $x = "this is a test", then intval($x) is 0. Since $x != intval($x), I don't consider it an integer. Here's the part I don't understand:

<?
$x = "this is a test";
echo "<p>\$x = " . $x;
echo "<p>intval(\$x) = " . intval($x);
if ($x == intval($x)) {
  echo "<p>\$x is an int";
}
?>

The output of this script is:

$x = this is a test
intval($x) = 0
$x is an int

How the heck is $x == intval($x) if $x = "this is a test" and intval($x) = 0?

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2000-02-12 07:32 UTC] torben at cvs dot php dot net
This is not a bug; it's a result of the way PHP automatically changes
a variable's type depending on context. For a full discussion of this, check
out http://www.php.net/manual/language.types.type-juggling.php3 and
http://www.php.net/manual/language.types.string.php3#LANGUAGE.TYPES.STRING.CONVERSION

The upshot is that if $x contains any string not starting with numeric
digits, it will be evaluated as '0' when referred to as an integer. Therefore
both the $x and the intval($x) in the comparison shown evaluate to 0,
and therefore the test returns true.
 [2000-02-13 13:10 UTC] danny at cvs dot php dot net
You can use strcmp() instead of ==, it is what I do.

Danny
---
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun May 19 17:01:33 2024 UTC