Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays not matching with strict comparison

Tags:

arrays

php

$c1 = $v1 = array();
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // prints false

$c1 === $v1 is false. But why? It seems that $v1 is automatically set to a different array then it's origin array automatically. Why it is happening?

Initially $c and $v1 is set to the same array instance. So if I mutate $v1 should not $c reflects the changes as they are set to the same array instance.

like image 547
sohan nohemy Avatar asked Jan 23 '26 14:01

sohan nohemy


1 Answers

These will not be the same, because you explicitly set them to hold different values. The first is empty, while the second holds values.

They are not set to the same reference though, so they are two different variables - when you do

$c1 = $v1 = array();

You create two different arrays. If you want the change of one to reflect in both arrays, you need to make it a reference, by using the & operator in front of the variable identifier, like so.

$v1 = array();
$c1 = &$v1; // $c1 is now a reference to $v1
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // true!

Notice that you need to reference it after the variable you wish to refer to has been made.

When using a reference like this, it goes both ways - any change to $v1 would be applied to $c1, and the other way around. So they are different variables, but will always hold the same values.

The comparison in the example above holds true because the arrays are exactly the same - not just by reference, but because they hold the same values and keys. If you compare two non-referenced arrays with the exact same values and exact same, matching keys, you would get a true equality too.

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

Live demo

  • Passing variables by reference
like image 104
Qirel Avatar answered Jan 26 '26 08:01

Qirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!