php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45297 Problem when comparing casted strings
Submitted: 2008-06-18 09:17 UTC Modified: 2008-06-18 09:27 UTC
From: wittstruck at mediafinanz dot de Assigned:
Status: Not a bug Package: Strings related
PHP Version: 5.2.6 OS: Windows XP
Private report: No CVE-ID: None
 [2008-06-18 09:17 UTC] wittstruck at mediafinanz dot de
Description:
------------
I'm casting a string to a double; afterwards the casted result does differ from the original string, but comparing them does not work properly and leads to a wrong bool.

strcmp works, though.

Reproduce code:
---------------
<?php

$stringAmount = '2008-06-13 14:24:00';

$doubleAmount = (double) $stringAmount;

echo 'doubleAmount: ' . $doubleAmount . ' stringAmount: ' .  $stringAmount;

if ($doubleAmount != $stringAmount)
{
    echo '<br/>' . $doubleAmount . ' is not equal to' . $stringAmount;
}
else
{
    echo "<br/> both are equal";
}

?>

Expected result:
----------------
doubleAmount: 2008 stringAmount: 2008-06-13 14:24:00
2008 is not equal to2008-06-13 14:24:00

Actual result:
--------------
doubleAmount: 2008 stringAmount: 2008-06-13 14:24:00
both are equal

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-06-18 09:23 UTC] colder@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

http://php.net/operators.comparison

if you compare a double with a string, the string is translated to a double first, use !==.



 [2008-06-18 09:27 UTC] wittstruck at mediafinanz dot de
!== will output the expected result, because the types are different, not because the content itself is different.

but you're right - when casting $doubleAmount to string afterwards everything is working as expected. 

even though this is (at least to me) a bug - a conversion from a string to a double will change the string, a conversion from a double to string works without changing the content of the double. so when comparing a double with a string, the double should be automatically casted to string - and not vice versa.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 20:01:29 2024 UTC