Arrays that do not match strict matching
$c1 = $v1 = array();
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // prints false
$c1 === $v1
is false. But why? It seems to be $v1
automatically set to another array and then to the original array. Why is this happening?
Initially $c
, and $v1
is established in the same array instance. So if I mutate $ v1 shouldn't $c
show the changes as they are set to the same array instance.
source to share
They are not the same thing because you explicitly set different values ββfor them. The first is empty and the second is values.
They are not set to the same reference, so they are two different variables - when you do
$c1 = $v1 = array();
You are creating two different arrays. If you want the change of one to appear in both arrays, you need to make a reference using an operator &
before the variable id, eg.
$v1 = array();
$c1 = &$v1; // $c1 is now a reference to $v1
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // true!
Note that you need to refer to it after the variable you want to refer to has changed.
When using a link like this, it goes both ways - any change to $v1
will be applied to $c1
, and vice versa. Thus, they are different variables, but will always have the same values.
The comparison in the above example makes sense because the arrays are exactly the same - not only by reference, but also because they contain the same values ββand keys. If you compare two unreferenced arrays with the same values ββand exactly the same as the corresponding keys, you also get true equality.
var_dump(array('foo') === array('bar')); // false; same keys, different values
var_dump(array('bar') === array('bar')); // true; same keys, same values
var_dump(array('bar') === array('baz' => 'bar')); // false; different keys, same value
source to share
These arrays will not be the same as the second array matters. Enter the following code:
<?php
$a = $b = [];
print_r($a);
print_r($b);
$result = ($a === $b) ? 1 : 0;
// The reasult will be 1 because the arrays are both empty.
print_r($result);
$b[0] = 'Ravi';
print_r($a);
print_r($b);
$result = ($a === $b) ? 1 : 0;
// The result will be 0 because the arrays are different.
print_r($result);
source to share