note 93404 added to function.array-unique

From: Date: Tue, 08 Sep 2009 15:24:20 +0000
Subject: note 93404 added to function.array-unique
Groups: php.notes 
Request: Send a blank email to php-notes+get-160303@lists.php.net to get a copy of this message
I'm not sure why you'd use any kind of loop to get the duplicates in an array. Here's a handy little function which does exactly that using some of PHP's other array_* functions. <?php function array_not_unique( $a = array() ) { return array_diff_key( $a , array_unique( $a ) ); } ?> Some arrays for testing: <?php $person = array(); $person[1] = "person_1"; $person[2] = "person_2"; $person[3] = "person_3"; $person[4] = "person_4"; $person[5] = "person_5"; $person[6] = "person_2"; # DUPE $person[7] = "person_4"; # DUPE $person[8] = "person_4"; # DUPE echo '<pre>',print_r(array_not_unique($person),1),'</pre>'; $person = array(); $person[] = 1; $person[] = 2; $person[] = 3; $person[] = 4; $person[] = 5; $person[] = 2; # DUPE $person[] = 4; # DUPE $person[] = 4; # DUPE echo '<pre>',print_r(array_not_unique($person),1),'</pre>'; ?> Output: Array ( [6] => person_2 [7] => person_4 [8] => person_4 ) Array ( [5] => 2 [6] => 4 [7] => 4 ) Hope it helps. --Bill ---- Server IP: 208.69.120.35 Probable Submitter: 98.235.179.75 ---- Manual Page -- http://www.php.net/manual/en/function.array-unique.php Edit -- https://master.php.net/note/edit/93404 Del: integrated -- https://master.php.net/note/delete/93404/integrated Del: useless -- https://master.php.net/note/delete/93404/useless Del: bad code -- https://master.php.net/note/delete/93404/bad+code Del: spam -- https://master.php.net/note/delete/93404/spam Del: non-english -- https://master.php.net/note/delete/93404/non-english Del: in docs -- https://master.php.net/note/delete/93404/in+docs Del: other reasons-- https://master.php.net/note/delete/93404 Reject -- https://master.php.net/note/reject/93404 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#160303) next »