Remove duplicate values from array in PHP

Remove duplicate values from array using PHP

Posted by Luke Beeno on September 4, 2022

Remove duplicate values from array in PHP

Remove duplicate values from array using PHP

Posted by Luke Beeno on September 4, 2022

Let us look at a few way in which you can remove duplicate values in PHP.

Option 1. Use a for loop

$arr=[5,11,6,8,2,5];
$newArr = [];

for($i=0; $i<count($arr); $i++) {  
   if (!in_array($arr[$i], $newArr)) {
      array_push($newArr, $arr[$i]);
   }
}
var_dump($newArr); //[5,11,6,8,2]

Option 2. Use array_unique() method

$arr=[5,11,6,8,2,5];

$newArr = array_unique($arr);
var_dump($newArr); //[5,11,6,8,2]

Option 3. Use array_flip() with array_values() method

$arr=[5,11,6,8,2,5];

$newArr = array_values( array_flip( array_flip( $arr ) ) );

var_dump($newArr); //[5,11,6,8,2]

 

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question