How to remove duplicate values from an array in PHP

You can use the PHP array_unique() function to remove the duplicate elements or values form an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys.

array_unique($array, $flags);

The array_unique() function has two parameters. The details of its parameters are as follows.

$array -   It is the array from which we want to remove the duplicate values. 

$flags  -    It specifies the sorting pattern for the array. The sorting flags are of five types. SORT_REGULAR compares items normally
SORT_NUMERIC compares items numerically
SORT_STRING compares items as strings
SORT_LOCALE_STRING compares items as strings, based on the current locale.

Example

<?php
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
 
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
?>

Output

Array ( [a] => moon [0] => star [2] => sky ) 


Example

<?php
$array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy","Daffodil","Daisy","Lili","Jasmine","Jasmine");
echo("Array before removal: \n");
var_dump($array);
$array = array_unique($array, SORT_NUMERIC);
echo("Array after removal: \n");
var_dump($array);
?>

Output

Array before removal:
array(11) {
  [0]=>
  string(4) "Rose"
  [1]=>
  string(4) "Lili"
  [2]=>
  string(7) "Jasmine"
  [3]=>
  string(8) "Hibiscus"
  [4]=>
  string(8) "Daffodil"
  [5]=>
  string(5) "Daisy"
  [6]=>
  string(8) "Daffodil"
  [7]=>
  string(5) "Daisy"
  [8]=>
  string(4) "Lili"
  [9]=>
  string(7) "Jasmine"
  [10]=>
  string(7) "Jasmine"
}
Array after removal:
array(1) {
  [0]=>
  string(4) "Rose"
}


The function has now sorted the array numerically.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...