What is the difference between == and === in PHP?
What would be some useful examples?
Additionally, how are these operators us
There are two differences between == and === in PHP arrays and objects that I think didn't mention here; two arrays with different key sorts, and objects.
If you have an array with a key sort and another array with a different key sort, they are strictly different (i.e. using ===). That may cause if you key-sort an array, and try to compare the sorted array with the original one.
For instance, consider an empty array. First, we try to push some new indexes to the array without any special sort. A good example would be an array with strings as keys. Now deep into an example:
// Define an array
$arr = [];
// Adding unsorted keys
$arr["I"] = "we";
$arr["you"] = "you";
$arr["he"] = "they";
Now, we have a not-sorted-keys array (e.g., 'he' came after 'you'). Consider the same array, but we sorted its keys alphabetically:
// Declare array
$alphabetArr = [];
// Adding alphabetical-sorted keys
$alphabetArr["I"] = "we";
$alphabetArr["he"] = "they";
$alphabetArr["you"] = "you";
Tip: You can sort an array by key using ksort() function.
Now you have another array with a different key sort from the first one. So, we're going to compare them:
$arr == $alphabetArr; // true
$arr === $alphabetArr; // false
Note: It may be obvious, but comparing two different arrays using strict comparison always results false. However, two arbitrary arrays may be equal using === or not.
You would say: "This difference is negligible". Then I say it's a difference and should be considered and may happen anytime. As mentioned above, sorting keys in an array is a good example of that.
Keep in mind, two different objects are never strict-equal. These examples would help:
$stdClass1 = new stdClass();
$stdClass2 = new stdClass();
$clonedStdClass1 = clone $stdClass1;
// Comparing
$stdClass1 == $stdClass2; // true
$stdClass1 === $stdClass2; // false
$stdClass1 == $clonedStdClass1; // true
$stdClass1 === $clonedStdClass1; // false
Note: Assigning an object to another variable does not create a copy - rather, it creates a reference to the same memory location as the object. See here.
Note: As of PHP7, anonymous classes was added. From the results, there is no difference between new class {} and new stdClass() in the tests above.