How to remove duplicate items from an array in PHP

Created at 22-Nov-2023 , By samar

In PHP, you can remove duplicate items from an array using the array_unique() function which is a in-built function in PHP. You can also use array_values(array_flip($originalArray)); to remove the duplicate items from original array in PHP.

  • Remove duplicate items from array using array_unique function

    You can use array_unique function to get the unique array items from array. You can use sort() method on $array or you can apply sort() method on $output to sort the array items in ascending order.

    $array = [1, 2, 4, 4, 5];
    $output = array_unique($array);
    print_r($output);
    

    Output :

    Array
    (
        [0] => 2
        [1] => 1
        [3] => 4
        [5] => 5
    )
    
  • Remove duplicate items from an array using array_values with array_flip function

    $originalArray = array(1, 2, 3, 4, 2, 5, 6, 1);
    $uniqueArray = array_values(array_flip($originalArray));
    print_r($uniqueArray);
    

    Output :

    Array
    (
        [0] => 7
        [1] => 4
        [2] => 2
        [3] => 3
        [4] => 5
        [5] => 6
    )
    
  • Remove duplicat items from array using in_array function in foreach loop

    $array = [2, 1, 2, 3, 3, 4, 5, 5 ,7 , 1];
    sort($array);
    $output = [];
    foreach($array as $arrItem){
    	if(!in_array($arrItem, $output)){
    		$output[] = $arrItem;
    	}
    }
    

    Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 7
    )
    

Back to code snippet queries related php

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.