PHP Remove Duplicate Values From Array Example


Share:
Published By: Admin, Published On: Apr 03, 2021, Category: PHP

Hello Friends,

Now let's see how to remove repeated or duplicate values from array you can use the PHP array_unique() function to remove the duplicate elements or values form an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

Note: The returned array will keep the first array item's key type.

Syntax:
array_unique(array, sorttype);

In this tutorial, I show how you can remove duplicate values from

  • An Indexed
  • Associative array
1. Indexed Array
<?php

    // Numberic array
    $num_arr = array(10,20,30,10,60,1,30,20);

    // Remove duplicate values
    $unique_num = array_unique($num_arr);

    print_r($unique_num);

?>
Output
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [4] => 60
    [5] => 1
)
2. Associative Array

NOTE – I passed SORT_REGULAR as second parameter in array_unique() method.

<?php

    $stu_arr[] = array("name" => "Parth","age"=>24);
    $stu_arr[] = array("name" => "Rahul","age"=>24);
    $stu_arr[] = array("name" => "Anil","age" => 23);
    $stu_arr[] = array("name" => "Rahul","age" => 24);

    $stu_arr1 = array_unique($stu_arr,SORT_REGULAR);
    print_r($stu_arr1);

?>
Output
Array
(
    [0] => Array
        (
            [name] => Parth
            [age] => 24
        )

    [1] => Array
        (
            [name] => Rahul
            [age] => 24
        )

    [2] => Array
        (
            [name] => Anil
            [age] => 23
        )

)

It will help you..

Share: