How to Remove duplicate values from an array in PHP

Learn How to Remove duplicate values from an array in PHP.


In PHP Programming Language, there is already a function to remove duplicate elements from an array. But unfortunately, array_unique does only support string based comparisons.

Check the following examples.


Array with duplicate values

<?php 
$Languages_list = array('PHP', 'Java', ' PHP', 'C++', ' C#');
$result = array_unique($Languages_list);
print_r($result);
?>


Output

 Array ([0] => PHP [1] => Java [2] => C++ [3] => C#) 


You can see it just output the PHP one time skipping the duplicate value. This is how array_unique PHP function works.

But this example was just a string based comparison. What to do in case of key based arrays.


Multi-dimensional array with duplicate values

<?php 
$data = array(
array('key1' => 'value1',    'key2' => 'same value for key2'),
array('key1' => 'value3',    'key2' => 'different value for key2'),
array('key1' => 'value1',    'key2' => 'same value for key2')
);
?> 


How to Remove duplicate values from above array?

You can use the uniqueness of array keys to solve this. Here is the solution:

<?php 
// walk input array 
$_data = array();
foreach ($data as $v) {
if (isset($_data[$v['key1']])) {
// found duplicate
continue;
}
// remember unique item
$_data[$v['key1']] = $v;
}
// if you need a zero-based array, otheriwse work with
$_data $data = array_values($_data);
print_r($data);
?>


This is how duplicates will be removed from the array. I hope it may help someone. If you want to learn PHP then checkout this list of best PHP learning resources.


Happy Coding!!!

Haroon Ejaz

A Software Engineer, primarily focusing on PHP development with over 3 years experience and a Bachelors degree in Information Technology.