PHP has no function build in that does this, but you can combine array_count_values and array_intersect to obtain the array(s) you want.
The first one is used to know which values do exist in your array (and counts them so it's easy to filter out every non-duplicate one), and the second function does preserve the keys. If you know the duplicated value upfront, you only need to use the latter:
$duplicatesArray = array_intersect($array, array($duplicate));
Full example:
/**
* @param array $array
* @param int $threshold (optional) minimum number of elements per group
* @return array
*/
function array_group_by_value(array $array, $threshold = 1)
{
$grouped = array();
foreach(array_count_values($array) as $value => $count)
{
if ($count < $threshold) continue;
$grouped[$value] = array_intersect($array, array($value));
}
return $grouped;
}
Usage Example:
$test = array('a', 'b', 'a', 'a', 'b', 'c');
var_dump(array_group_by_value($test, 2));
Output:
array(2) {
["a"]=>
array(3) {
[0]=>
string(1) "a"
[2]=>
string(1) "a"
[3]=>
string(1) "a"
}
["b"]=>
array(2) {
[1]=>
string(1) "b"
[4]=>
string(1) "b"
}
}