php duplicate array code example

Example 1: php remove duplicates from array

<?php
$fruits_list = array('Orange',  'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
  
Output:

Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )

Example 2: get duplicate value from array php

$arr = array(1, 4, 6, 1, 8, 9, 4, 6);

$unique = array_unique($arr);

$duplicates = array_diff_assoc($arr, $unique);

print_r($duplicates);
Array ( [3] => 1 [6] => 4 [7] => 6 )

Example 3: check duplicate data in array php

$counts = array_count_values($array);
            $duplicate_title  = array_filter($array, function ($value) use ($counts) {
                return $counts[$value] > 1;
            });

Example 4: copy php array to another

$arr1 = ['a'=>1, 'b'=>2, 'c'=>3];
$arr2 = $arr1;

unset($arr2['a'];
print_r($arr1);
//['b'=>2, 'c'=>3]
// ------- OR -------
$arr2 = clone $arr1;

unset($arr2['a'];
print_r($arr1);
//['a'=>1, 'b'=>2, 'c'=>3]

Example 5: php check for duplicates in array

function has_dupes($array) {
    $dupe_array = array();
    foreach ($array as $val) {
        if (++$dupe_array[$val] > 1) {
            return true;
        }
    }
    return false;
}

Tags:

Php Example