Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime Comparison

I've become accostomed to using the identical comparison operator in PHP (===), instead of the equal comparison operator (==). I ran into an issue while using php's built in DateTime objects. I'm confused as to why the equal comparison return true, but the identical comparison return false in the following code?

Code:

$test1 = new DateTime("now");       // What I thought were identical objects
$test2 = new DateTime("now");       // 
$test3 = new DateTime("tomorrow");

echo("test1: ");
var_dump($test1);
echo("<br/>test2: ");
var_dump($test2);

echo("now === now: ");
var_dump($test1 === $test2);

echo("<br/>now == now: ");
var_dump($test1 == $test2);

echo("<br/>now < now: ");
var_dump($test1 < $test2);

echo("<br/>now > now: ");
var_dump($test1 > $test2);

echo("<br/>now < tomorrow: ");
var_dump($test2 < $test3);

echo("<br/>now > tomorrow: ");
var_dump($test2 > $test3);

Output:

    test1: object(DateTime)#36 (3) { ["date"]=> string(19) "2015-06-23 14:44:25" ["timezone_type"]=> int(3) ["timezone"]=> string(15) "America/Chicago" } 
    test2: object(DateTime)#37 (3) { ["date"]=> string(19) "2015-06-23 14:44:25" ["timezone_type"]=> int(3) ["timezone"]=> string(15) "America/Chicago" } 
    now === now: bool(false) 
    now == now: bool(true) 
    now < now: bool(false) 
    now > now: bool(false) 
    now < tomorrow: bool(true) 
    now > tomorrow: bool(false)
like image 509
SerEnder Avatar asked Sep 27 '22 13:09

SerEnder


1 Answers

In case of object comparision === not only check value and object type but it will check references also. That's why in your case === returns false because of two separate instance.

Just to clarify check this out:-

https://eval.in/386378

Note:- In the first case two separate instances are there $test1 and $test2, that's why === returns false even object type and there values are equal.

But in the second case since $test1 and $test2 are same references so it states true.

Also in case of normal variables === check only value and datatype. where as == always checks values only and whenever datatype will different it will not give correct output. So be careful when using ==. Thanks.

like image 129
Anant Kumar Singh Avatar answered Oct 03 '22 07:10

Anant Kumar Singh