How to find duplicate values in an array
Short answer
Count how often each value occurs and keep those above one:
<?php
$emails = ['a@x.com', 'b@x.com', 'a@x.com', 'c@x.com', 'b@x.com'];
$duplicates = array_keys(array_filter(array_count_values($emails), fn ($count) => $count > 1));
echo implode(', ', $duplicates);Output:
a@x.com, b@x.comAre there any repeats at all
Compare the length of the array with its length without repeats:
<?php
$ids = [3, 7, 3, 9];
var_dump(count($ids) !== count(array_unique($ids)));Output:
bool(true)Functions used in this recipe
- array_count_values — Counts how many times each value occurs.
- array_filter — Keeps the array elements that pass a test.
- array_unique — Removes duplicate values from an array.