Identical arrays vs equal arrays

There is a small problem when comparing arrays -- you can find arrays where array_diff comes back empty and yet, the arrays are not identical.

<?php
$array1
= array(
 
'foo' => 'foo',
 
'bar' => 'bar',
);

$array2 = array(
 
'bar' => 'bar',
 
'foo' => 'foo',
);

var_dump(array_diff($array1, $array2)); // Result: empty array.
var_dump($array1 == $array2); // Result: true.
var_dump($array1 === $array2); // Result: false.
?>

The behavior is logical when the arrays (seemingly) have no keys.

<?php
$array1
= array(
 
'foo',
 
'bar',
);

$array2 = array(
 
'bar',
 
'foo',
);

var_dump(array_diff($array1, $array2)); // Result: empty array.
var_dump($array1 == $array2); // Result: false.
var_dump($array1 === $array2); // Result: false.
?>

Since

<?php
$array1
[0] != $array2[0];
?>

but slightly less so when the arrays are associative. In the first example:
<?php
$array1
['foo'] === $array2['foo'];
$array1['bar'] === $array2['bar'];
?>

Moral of the story: be careful with using identical on associative arrays.

Comments

hehe

Does your brain see difference in ordering? it may have same keys and values but ordering is not the same, so not identical. When you do foreach, it will be different first.

There is only one problem with php, a caveman can write php code! Because of that many cavemen write some stuff and after a while they think they are real programmers

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options