Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Remove duplicated elements of associative array in PHP
In PHP, removing duplicated elements from associative arrays requires special handling since standard functions like array_unique() work only with simple values. For complex associative arrays, you need to serialize the arrays first, remove duplicates, then unserialize them back.
Syntax
The general approach combines array_map(), serialize(), array_unique(), and unserialize() functions −
array_map("unserialize", array_unique(array_map("serialize", $array)))
Example
Here's how to remove duplicate associative arrays from a multidimensional array −
<?php
$result = array(
0 => array('a' => 1, 'b' => 'Hello'),
1 => array('a' => 1, 'b' => 'duplicate_val'),
2 => array('a' => 1, 'b' => 'duplicate_val'),
3 => array('a' => 2, 'b' => 'World')
);
echo "Original array:<br>";
print_r($result);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
echo "\nArray after removing duplicates:<br>";
print_r($unique);
?>
Original array:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => duplicate_val
)
[2] => Array
(
[a] => 1
[b] => duplicate_val
)
[3] => Array
(
[a] => 2
[b] => World
)
)
Array after removing duplicates:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => duplicate_val
)
[3] => Array
(
[a] => 2
[b] => World
)
)
How It Works
The process works in four steps:
-
array_map("serialize", $result)− Converts each associative array to a string representation -
array_unique()− Removes duplicate string values -
array_map("unserialize", ...)− Converts the unique strings back to associative arrays - Original array keys are preserved where duplicates are removed
Conclusion
This serialize/unserialize approach effectively removes duplicate associative arrays by converting them to comparable string representations. The method preserves original array structure while eliminating exact duplicates based on both keys and values.
