Skip to content

How to Remove Duplicates From Multidimensional Array, PHP

Removing duplicates from the flatten array is simple and we have a built-in function for it. The array_unique function removes duplicates from the one-dimensional array. 

we gonna use array_unique function along with array_mapserialize and unserialize to remove duplicates from the multidimensional PHP array.

<?php
function array_multidimensional_unique($input){
     $output = array_map("unserialize",
     array_unique(array_map("serialize", $input)));
   return $output;
}

$input = [
    ['name' => 'PHP' ],
    ['name' => 'Laravel' ],
    ['name' => 'CodeIgnier'],
    ['name' => 'PHP' ],
    ['name' => 'Laravel' ],
    ['name' => 'CodeIgnier'],
];

$output = array_multidimensional_unique($input);

print_r($output);

// Array
// (
//     [0] => Array
//         (
//             [name] => PHP       
//         )

//     [1] => Array
//         (
//             [name] => Laravel   
//         )

//     [2] => Array
//         (
//             [name] => CodeIgnier
//         )

// )


array_map — Applies the callback to the elements of the given array

serialized — Generates a storable representation of a value

unserialize — Creates a PHP value from a stored representation

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments