note 71719 modified in function.array-unique by danbrown

From: Date: Sun, 23 Jan 2011 17:22:43 +0000
Subject: note 71719 modified in function.array-unique by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176192@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; 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: <?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. http://php.net/manual/en/function.array-unique.php

« previous php.notes (#176192) next »