Removing duplicate elements from an array in PHP

PHPServer Side ProgrammingProgramming

The ‘array_flip’ function can be used, that will reverse the values as indices and keys as values.

Example

 Live Demo

<?php
   $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68);
   echo "The original array contains \n";
   print_r($my_arr);
   $my_arr = array_flip($my_arr);
   $my_arr = array_flip($my_arr);
   $my_arr= array_values($my_arr);
   echo "\n The array after removing duplicate elements is \n ";
   print_r($my_arr);
?>

Output

The original array contains
Array
(
   [0] => 45
   [1] => 65
   [2] => 67
   [3] => 99
   [4] => 81
   [5] => 90
   [6] => 99
   [7] => 45
   [8] => 68
)

The array after removing duplicate elements is
Array
(
   [0] => 45
   [1] => 65
   [2] => 67
   [3] => 99
   [4] => 81
   [5] => 90
   [6] => 68
)

An array is defined and duplicate elements from the array can be found and removed using the ‘array_flip’ function, that basically reverses the keys/index as values and values as keys. This way, the value that is repeated comes twice in the index and one of them is removed since indices have to be unique. Again, the ‘array_flip’ function is used to get the array back to the original form.

raja
Published on 01-Jul-2020 10:53:01
Advertisements