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
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: 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

Pull Requests

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-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 07 12:01:35 2025 UTC