Reputation: 21
I'm trying to learn a little bit of php and can not understand why the 2 second IF is executing here. I have a variable $theDate set to accept a European date 4th May 2010.
$theDate = date('d-m-Y', strtotime("04-05-2010"));
echo "$theDate<br />";
if($theDate > "02-05-2010")
{
echo "Greater than!<br />";
}
if($theDate > "02-05-2011")
{
echo "Why am I showing<br />";
}
echo "Endof";
I just want to use IFs for now, no IF-Else etc. But why is the 2nd IF executing when $theDate is NOT greater than 02-05-2011,
thanks in advance,
Joe
Upvotes: 1
Views: 125
Reputation: 2789
As far as I remember its 2014. Why not use DateTime object and do why not do it right way??
$raw = '04-05-2010';
$theDate= \DateTime::createFromFormat('d-m-Y', $raw);
$raw2 = '02-05-2010';
$anotherDate = \DateTime::createFromFormat('d-m-Y', $raw2);
echo 'theDatedate: ' . $theDate->format('m/d/Y') . "<br>";
echo 'anotherDate date: ' . $anotherDate ->format('m/d/Y') . "<br>";
if ($theDate > $anotherDate ) {
echo "Greater than!<br />";
}
If you are learning php please check this resource, is worth reading.
Upvotes: 3
Reputation: 1545
To compare dates as string just use the UTC format YYYY-MM-DD. If you want to compare it as integer you have to convert it to seconds or compare starting with the year and then with the month and so on---
Upvotes: 2
Reputation: 396
You are comparing strings. Convert Date to seconds and then compare, working one for all formats etc.
$theDate = date('d-m-Y', strtotime("04-05-2010"));
echo "$theDate<br />";
if(strtotime($theDate) > strtotime("02-05-2010"))
{
echo "Greater than!<br />";
}
if(strtotime($theDate) > strtotime("02-05-2011"))
{
echo "Why am I showing<br />";
}
echo "Endof";
Upvotes: 1
Reputation: 476557
It uses string comparison. Thus it first looks at the first character, if that is greater than, true
is returned. If less, false
is returned. If equal, move to the next character.
You can solve this by formatting the string in reverse: Y-m-d
. Or by using a built-in operator:
if($time > strtotime($text))
where $time
is specified in seconds.
Upvotes: 1