Page 1 of 1

String comparison to 0 returning true

Posted: Tue Jan 16, 2007 11:14 am
by RobertGonzalez
Can someone help me understand this? I have the following code:

Code: Select all

<?php
// Users last accept date
$user_last_accept_date = (trim($userdata['use_plcy_dttm']));
?>
The value of $userdata['use_plcy_dttm'] for the account I am testing is: Dec 28 2006 1:19PM (after the trim). A var dump of the array value and the assigned var value:

Code: Select all

<?php
echo '<pre>'; var_dump($userdata['use_plcy_dttm']); echo '</pre>';
echo '<pre>'; var_dump($user_last_accept_date); echo '</pre>';
?>
Returns:
string(19) "Dec 28 2006 1:19PM"
string(19) "Dec 28 2006 1:19PM"
So why, when I run this conditional, do I get a boolean true on my comparison?

Code: Select all

<?php
if (0 == $user_last_accept_date)
{
	//$user_last_accept_date = 'Jan 1, 1970 1:00AM';
	echo $user_last_accept_date . ' shows as 0 (' . var_dump(($user_last_accept_date == 0)) . ')...<br />'; 
}
?>
Return:
bool(true) Dec 28 2006 1:19PM shows as 0 ()...
What the heck am I doing wrong? I know it is simple, and I am sure I am doing something utterly stupid because logically this makes no sense to me. Here is the code in full, as it written before seeing this issue:

Code: Select all

<?php
/*
    Everah |
    For testing, assume value of $userdata['use_plcy_dttm] = 'Dec 28 2006 1:19PM'
*/
// Users last accept date
$user_last_accept_date = (trim($userdata['use_plcy_dttm']));
if (0 == $user_last_accept_date)
{
	//$user_last_accept_date = 'Jan 1, 1970 1:00AM';
}
?>

Posted: Tue Jan 16, 2007 12:39 pm
by aaronhall
Type juggling problem. Try:

Code: Select all

<?php
var_dump((int)$user_last_accept_date);
?>
PHP is casting the string as an integer before the comparison.

Using the following would return false:

Code: Select all

<?php
var_dump($user_last_accept_date === 0);
?>
Here's some more on the topic: http://us3.php.net/manual/en/language.t ... conversion

Posted: Tue Jan 16, 2007 3:56 pm
by RobertGonzalez
I swear I have never run in to this issue before. But I guess that the behavior is as expected.

Thanks for the link.