note 85109 modified in function.array-unique by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 Nov 2008 14:51:40 +0000 |
| Subject: | note 85109 modified in function.array-unique by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146240@lists.php.net to get a copy of this message | ||
Here's another solution for returning an array that only includes repeated values. There is one
given below but it only works on numerically indexed arrays; this one is more comprehensive since I
used the foreach iterator. Also, this one preserves keys--in that the returned result contains a
distinct list of repeats (storing only the first instance it encounters of each duplicate value).
<?php
function array_repeated($array)
{
if ( !is_array($array) ) {
return false;
}
$duplicates = array();
foreach ( $array as $key => $val ) {
end($array);
$k = key($array);
$v = current($array);
while ( $k !== $key ) {
if ( $v === $val ) {
$duplicates[$key] = $v;
break;
}
$v = prev($array);
$k = key($array);
}
}
return $duplicates;
}
?>
--was--
Here's another solution for returning an array that only includes repeated values. There is one
given below but it only works on numerically indexed arrays; this one is more comprehensive since I
used the foreach iterator. Also, this one preserves keys--in that the returned result contains a
distinct list of repeats (storing only the first instance it encounters of each duplicate value).
<?php
function array_repeated($array)
{
if ( !is_array($array) ) {
return false;
}
$duplicates = array();
foreach ( $array as $key => $val ) {
end($array);
$k = key($array);
$v = current($array);
while ( $k !== $key ) {
if ( $v === $val ) {
$duplicates[$key] = $v;
}
$v = prev($array);
$k = key($array);
}
}
return $duplicates;
}
?>
http://php.net/manual/en/function.array-unique.php