What function in PHP can be used as the opposite of array_unique()?
When we want to remove duplicate values from an array in PHP, we can use the array_unique() function. However, if we want to do the opposite and keep only the duplicate values, there is no built-in function for that in PHP. To achieve this, we can write a custom function that iterates through the array, keeping track of the values that have duplicates and returning them in a new array.
function get_duplicate_values($array) {
$duplicates = array();
$counts = array_count_values($array);
foreach ($counts as $value => $count) {
if ($count > 1) {
$duplicates[] = $value;
}
}
return $duplicates;
}
$array = array(1, 2, 2, 3, 4, 4, 5);
$duplicate_values = get_duplicate_values($array);
print_r($duplicate_values);
Related questions
-
PHPUnit code coverage PHPUnit.xml
-
SQL queries optimization PHP scripts
-
MySQL query execution time PHP scripts