note 40685 modified in function.array-unique by vrana

From: Date: Tue, 17 Aug 2004 14:50:19 +0000
Subject: note 40685 modified in function.array-unique by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-79998@lists.php.net to get a copy of this message
If you need to have the keys of the duplicates in an array returned, you may find this function useful: <?php function unique_events($array){ //checks $array for duplicate values and returns an //array containing the keys of duplicates $count= array_intersect_assoc($array, array_flip( array_count_values($array))); foreach($array as $key=>$value){ if (in_array($value,$count)){ $return[$value][]=$key; } } return $return; } ?> Example: Input: Array ( [0] => 44 [1] => 23 [2] => 23 [3] => 23 [4] => 9 [5] => 9 [6] => 9 [7] => 9 [8] => 9 [9] => 9 [10] => 9 [11] => 9 ) Function returns: Array ( [23] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [9] => Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 7 [4] => 8 [5] => 9 [6] => 10 [7] => 11 ) ) --was-- If you need to have the keys of the duplicates in an array returned, you may find this function useful: function unique_events($array){ //checks $array for duplicate values and returns an //array containing the keys of duplicates $count= array_intersect_assoc($array, array_flip( array_count_values($array))); foreach($array as $key=>$value){ if (in_array($value,$count)){ $return[$value][]=$key; } } return $return; } Example: Input: Array ( [0] => 44 [1] => 23 [2] => 23 [3] => 23 [4] => 9 [5] => 9 [6] => 9 [7] => 9 [8] => 9 [9] => 9 [10] => 9 [11] => 9 ) Function returns: Array ( [23] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [9] => Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 7 [4] => 8 [5] => 9 [6] => 10 [7] => 11 ) ) http://php.net/manual/en/function.array-unique.php

« previous php.notes (#79998) next »