php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #66211 integer/string comparisons have bad type-casting
Submitted: 2013-12-01 02:14 UTC Modified: 2013-12-01 02:58 UTC
From: php at charles-chandler dot org Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.4.22 OS: Mac OSX
Private report: No CVE-ID: None
 [2013-12-01 02:14 UTC] php at charles-chandler dot org
Description:
------------
---
From manual page: http://www.php.net/types.comparisons
---

2 == '2b'

I understand why, in a loosely typed language, 2 == '2', but it doesn't make sense for an integer to be equal-equal to a string that simply begins with an integer, such as 2 == '2b', so this looks like a bug to me. Rather than casting the string to an integer (i.e., intval('2b') == 2), the integer should cast to a string for the comparison (i.e., strval(2) != '2b'). 

Tested in PHP 5.2.5 and 5.3.13.



Test script:
---------------
<?php

// this is the problem, which we'd expect 
// to return false, but which returns true:
echo (2 == '2b').'<br />';

// this is probably what's happening:
echo (2 == intval('2b')).'<br />';

// this is what probably should happen:
echo (strval(2) != '2b').'<br />';

?>


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-12-01 02:58 UTC] yohgaki@php.net
-Status: Open +Status: Not a bug -Type: Bug +Type: Feature/Change Request
 [2013-12-01 02:58 UTC] yohgaki@php.net
PHP converts "integer like string to integer" and PHP is designed to do so.

Use === or !== for stricter comparison.

Added to wiki
https://wiki.php.net/rfc/comparison_inconsistency?&#conversioncomparison
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat Sep 25 01:03:38 2021 UTC