PHP array_unique Function – Remove duplicate elements from array in php

PHP array_unique function tutorial explain you how to remove duplicate elements or values from an array in PHP. This tutorial demostrate you how to remove duplicate elements/values from an array without using any function in PHP.

PHP Array_unique() function

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

The basic Syntax of php array_unique function:

array_unique(array, sorttype)

Parameter Values:

ParameterDescription
arrayRequired. Specifying an array
sorttypeOptional. Specifies how to compare the array elements/items. Possible values:
1). SORT_STRING – Default. Compare items as strings
2). SORT_REGULAR – Compare items normally (don’t change types)
3). SORT_NUMERIC – Compare items numerically
4). SORT_LOCALE_STRING – Compare items as strings, based on current locale

Remove Duplicate elements from an array PHP

Example – Using Array_unique() function, remove values or elements from an array.

<?php
$arr = array("a"=>"java","b"=>"php","c"=>"laravel","d"=>"codeigniter","e"=>"java", "f"=>"laravel");
print_r(array_unique($arr));
?>

Output:

Array ( [a] => java [b] => php [c] => laravel [d] => codeigniter )

Remove duplicate elements from an array without using the array function

Here we will take few examples for remove elements from an array without using any PHP functions.

Example 1:

<?php
$arr = array("a"=>"java","b"=>"php","c"=>"laravel","d"=>"codeigniter","e"=>"java", "f"=>"laravel");
$newArr = array();
 
foreach($arr as $inputArrayItem) {
    foreach($newArr as $outputArrayItem) {
        if($inputArrayItem == $outputArrayItem) {
            continue 2;
        }
    }
    $newArr[] = $inputArrayItem;
}
print_r($newArr);
?>

Output:

Array ( [0] => java [1] => php [2] => laravel [3] => codeigniter )

Example 2:

<?php
 $arr = array("a"=>"java","b"=>"php","c"=>"laravel", "d"=>"codeigniter","e"=>"java", "f"=>"laravel");
 
 $count = count($arr);
 
 $outputArr = [];
 
 foreach($arr as $key => $arrVal) {
    if(!in_array($arrVal, $outputArr)){
        array_push($outputArr, $arrVal);
    }
 }
 print_r ($outputArr);
?>

Output:

Array ( [0] => java [1] => php [2] => laravel [3] => codeigniter )

So today you have learned to php array_unique function to remove Duplicate elements from an array in PHP without using any function.

Leave a Comment