note 121089 deleted from language.operators.comparison by cmb
| From: | cmb@php.net | Date: | Tue, 05 Nov 2019 14:44:08 +0000 |
| Subject: | note 121089 deleted from language.operators.comparison by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212937@lists.php.net to get a copy of this message | ||
Note Submitter: fr at felix-riesterer dot de
----
I wanted to see if two arrays carry the same information even if they are technically different, so
I created the following function. Hopefully this is useful to somebody.
Note: This is a different approach than "rshawiii at yahoo dot com" has taken.
<?php
/**
* function to compare the contents of two arrays
*
* This function returns true if all the following are true:
* - arrays' values match
* - arrays' keys match
* - keys-value pairs are the same in both arrays
*
* The order of the key-value pairs does not matter, so even if
* ($array1 == $array2) is technically false, this function might
* still return true like in the following examples:
*
* $a = array(1, 5, 8);
* $b = array(5, 1, 8);
* => true
*
* $a = array('a' => 1, 'b' => 2, 'c' => 'xyz');
* $b = array('a' => 1, 'c' => 'xyz', 'b' => 2);
* => true
*
* $a = array(4 => 1, 7 => 2, 12 => 'xyz');
* $b = array(9 => 2, 3 => 1, 123 => 'xyz');
* => false
*
* @param array
* @param array
* @return bool matching
*/
function same_array_contents($a, $b) {
// easy
if (count($a) != count($b)) {
return false;
}
// complicated 1: different values
$a_values = array_values($a);
$b_values = array_values($b);
sort($a_values);
sort($b_values);
if ($a_values != $b_values) {
return false;
}
// complicated 2: different index names
$a_keys = array_keys($a);
$b_keys = array_keys($b);
sort($a_keys);
sort($b_keys);
if ($a_keys != $b_keys) {
return false;
}
// complicated 3 (same values and same keys): key => value different?
$r = true; // expect match
if (array_keys($a_keys) != $a_keys
|| array_keys($b_keys) != $b_keys
) {
// associative array(s)
foreach ($a_keys as $key) {
if ($a[$key] != $b[$key]) {
$r = false;
}
}
}
return $r;
}
?>