String comparison to 0 returning true

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

String comparison to 0 returning true

Post 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';
}
?>
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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.
Post Reply