note 94596 added to function.array-diff

From: Date: Fri, 13 Nov 2009 12:24:41 +0000
Subject: note 94596 added to function.array-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-162862@lists.php.net to get a copy of this message
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) ?> ---- Server IP: 195.221.21.36 Probable Submitter: 82.229.167.16 ---- Manual Page -- http://www.php.net/manual/en/function.array-diff.php Edit -- https://master.php.net/note/edit/94596 Del: integrated -- https://master.php.net/note/delete/94596/integrated Del: useless -- https://master.php.net/note/delete/94596/useless Del: bad code -- https://master.php.net/note/delete/94596/bad+code Del: spam -- https://master.php.net/note/delete/94596/spam Del: non-english -- https://master.php.net/note/delete/94596/non-english Del: in docs -- https://master.php.net/note/delete/94596/in+docs Del: other reasons-- https://master.php.net/note/delete/94596 Reject -- https://master.php.net/note/reject/94596 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#162862) next »