note 88892 added to function.array-diff

From: Date: Thu, 12 Feb 2009 11:20:15 +0000
Subject: note 88892 added to function.array-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-150564@lists.php.net to get a copy of this message
I needed a function which compares $arr1 with $arr2 and return all values from $arr2 that aren't in $arr1. Additionally the function has to compares multiarrays to. Here is it: <?php function arr_diff($a1,$a2){ $ar = array(); foreach ($a2 as $k => $v) { if (!is_array($v)) { if ($v !== $a1[$k]) $ar[$k] = $v; }else{ if ($arr = arr_diff($a1[$k], $a2[$k])) $ar[$k] = $arr; } } return $ar; } // example: $arr1 = array( 'user1' => array( 'name' => 'john d.', 'street' => 'elmstreet no. 2', 'city' => 'berlin' ), 'user2' => array( 'name' => 'harald c.', 'street' => 'b-street no. 7', 'city' => 'cologne' ) ); $arr2 = array( 'user1' => array( 'name' => 'john b.', // change #1 'street' => 'elmstreet no. 2', 'city' => 'berlin' ), 'user2' => array( 'name' => 'harald c.', 'street' => 'b-street no. 7', 'city' => 'bavaria' // change #2 ) ); print_r(arr_diff($arr1, $arr2)); /* will output: Array ( [user1] => Array ( [name] => john b. ) [user2] => Array ( [city] => bavaria ) ) */ ?> maybe someone can need this, for my usage it works proper. regards ---- Server IP: 217.160.72.57 Probable Submitter: 62.220.15.178 ---- Manual Page -- http://www.php.net/manual/en/function.array-diff.php Edit -- https://master.php.net/note/edit/88892 Del: integrated -- https://master.php.net/note/delete/88892/integrated Del: useless -- https://master.php.net/note/delete/88892/useless Del: bad code -- https://master.php.net/note/delete/88892/bad+code Del: spam -- https://master.php.net/note/delete/88892/spam Del: non-english -- https://master.php.net/note/delete/88892/non-english Del: in docs -- https://master.php.net/note/delete/88892/in+docs Del: other reasons-- https://master.php.net/note/delete/88892 Reject -- https://master.php.net/note/reject/88892 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#150564) next »