
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Duplicate Elements from an Array in PHP
The ‘array_flip’ function can be used, that will reverse the values as indices and keys as values.
Example
<?php $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68); echo "The original array contains
"; print_r($my_arr); $my_arr = array_flip($my_arr); $my_arr = array_flip($my_arr); $my_arr= array_values($my_arr); echo "
The array after removing duplicate elements is
"; 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.
Advertisements