note 71719 modified in function.array-unique by james

From: Date: Fri, 19 Oct 2007 02:12:02 +0000
Subject: note 71719 modified in function.array-unique by james
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-131527@lists.php.net to get a copy of this message
What if I only want the duplicated items, not the unique ones? I tried to do it by using array_diff of an array and its unique, but it did not work (any help?); so I made this function with a relatively good efficiency: <?php function array_repeated($array) { if(!is_array($array)) return false; $repeated_values = Array(); $array_unique = array_unique($array); if(count($array)-count($array_unique)) { for($i=0;$i<count($array);$i++) { if(!array_key_exists($i, $array_unique)) $repeated_values[] = $array[$i]; } } return $repeated_values; } ?> This function is based on the behaviour of the array_unique function that mantains the indexes of the array when deleting the item. --was-- What if I only want the duplicated items, not the unique ones? I tried to do it by using array_diff of an array and its unique, but it did not work (any help?); so I made this function with a relatively good efficiency: function array_repeated($array) { if(!is_array($array)) return false; $repeated_values = Array(); $array_unique = array_unique($array); if(count($array)-count($array_unique)) { for($i=0;$i<count($array);$i++) { if(!array_key_exists($i, $array_unique)) $repeated_values[] = $array[$i]; } } return $repeated_values; } This function is based on the behaviour of the array_unique function that mantains the indexes of the array when deleting the item. http://php.net/manual/en/function.array-unique.php

« previous php.notes (#131527) next »