Categories
PHP / MySQL

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

By Praveen Anaparthi

11+ years of IT industry experience holding a wide range of skill sets and roles with significant work on PHP, Node.js, Python, Ruby, Docker, React.js, Microsoft Azure, Azure DevOps, Windows PowerShell, Shell script, Jenkins, MongoDB, SQL, MySQL, Apache, Nginx. etc. It is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

Leave a Reply

Your email address will not be published.