note 94596 deleted from function.array-diff by cmb
| From: | cmb@php.net | Date: | Tue, 05 Nov 2019 14:49:26 +0000 |
| Subject: | note 94596 deleted from function.array-diff by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212944@lists.php.net to get a copy of this message | ||
Note Submitter: pikiou at somethinggooglerelated dot com
----
With previous solutions handling multi-dimensional arrays or objects through serialization, if
compared variables contain references at some point, these will be serialized and stand as such
after the diff function.
Here is a safer solution :
<?php
function array_diff_no_cast(&$ar1, &$ar2) {
$diff = Array();
foreach ($ar1 as $key => $val1) {
if (array_search($val1, $ar2) === false) {
$diff[$key] = $val1;
}
}
return $diff;
}
?>
Example:
<?php
$referenced = Array(1,1);
$array1 = Array(&$referenced, Array(2,3));
$array2 = Array(Array(1,1), Array(4,5));
$result = array_diff_no_cast($array1, $array2);
print_r($result); //Outputs Array(1 => Array(2,3))
//And $referenced stands unchanged (not serialized)
?>