Remove duplicate values from an array in PHP

You can use the PHP array_unique() function remove 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.

array_unique() through we can get only unique value from an array.

First let’s see the $stack array output :

<?php
$stack = array("green", "red", "green", "yellow", "red");
print_r($stack);
?>

Output:

Array
(
    [0] => green
    [1] => red
    [2] => green
    [3] => yellow
    [4] => red
)

In the above output $stack array have 5 elements and in this output found “green” value two times in an array.

Use array_unique() function Remove duplicate values from an array in PHP

But when we use array_unique() function then it will return only unique value as below output:

<?php 
$arr = array("green", "red", "green", "yellow", "red"); 
$result = array_unique($arr); // Deleting the duplicate items 
print_r($result); 
?>

Output:

Array
(
    [0] => green
    [1] => red
    [3] => yellow
)

Leave A Reply

Your email address will not be published.