使用array_count_values
是最简单的方法,但如果您需要掌握如何完成您正在寻找的内容,这里是详细版本。
$input = array(1, 2, 3, 4, 1);
$unique = array_unique($input);
// If $input and $unique are different in length,
// there is one or more repeating values
if (count($input) !== count($unique)) {
$repeat = array();
// Sort values in order to have equal values next to each other
sort($input);
for ($i = 1; $i < count($input) - 1; $i++) {
// If two adjacent numbers are equal, that's a repeating number.
// Add that to the pile of repeated input, disregarding (at this stage)
// whether it is there already for simplicity.
if ($input[$i] === $input[$i - 1]) {
$repeat[] = $input[$i];
}
}
// Finally filter out any duplicates from the repeated values
$repeat = array_unique($repeat);
echo implode(', ', $repeat);
} else {
// All unique, display all
echo implode(', ', $input);
}
简洁的单线版本将是:
$input = array(1, 2, 3, 4, 1);
$repeat = array_keys(
array_filter(
array_count_values($input),
function ($freq) { return $freq > 1; }
)
);
echo count($repeat) > 0
? implode(', ', $repeat)
: implode(', ', $input);