+4 votes
in Programming Languages by (54.2k points)
How can I remove duplicate values from a PHP array? What PHP function should be used?

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

To remove duplicate values from a PHP array, the array_unique() function can be used. This function keeps the first occurrence of the value and deletes others.

Here is an example of the array_unique() function using an indexed array and an associative array:

<?php
$arr1 = array(1,2,2,1,3,3,2,4,4,5,5,4);
$arr2 = array("a"=>1, "b"=>2, "c"=>3, "d"=>2, "e"=>4, "f"=>5, "g"=>3, "h"=>1);

print_r(array_unique($arr1));
print_r(array_unique($arr2));
?>

The output of the above code:

Array
(
    [0] => 1
    [1] => 2
    [4] => 3
    [7] => 4
    [9] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [e] => 4
    [f] => 5
)


...