Home > Backend Development > PHP Tutorial > How to Efficiently Remove Duplicate Arrays from a Multi-Dimensional Array in PHP?

How to Efficiently Remove Duplicate Arrays from a Multi-Dimensional Array in PHP?

Susan Sarandon
Release: 2024-12-24 11:39:23
Original
847 people have browsed it

How to Efficiently Remove Duplicate Arrays from a Multi-Dimensional Array in PHP?

Removing Duplicates from Multi-Dimensional Arrays in PHP

When working with multi-dimensional arrays, it can be necessary to eliminate duplicate values to ensure data integrity. Here's an efficient approach to achieve this in PHP.

Using array_map and serialize

We can leverage the array_map function to apply the serialize function to each array in the multi-dimensional array. Serializing converts each array to a unique string representation. Then, array_unique eliminates duplicate string representations. Finally, we unserialize the unique strings back into their corresponding arrays.

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Copy after login

Example

Let's consider an example multi-dimensional array.

$input = [
    [0 => 'abc', 1 => 'def'],
    [0 => 'ghi', 1 => 'jkl'],
    [0 => 'mno', 1 => 'pql'],
    [0 => 'abc', 1 => 'def'],
    [0 => 'ghi', 1 => 'jkl'],
    [0 => 'mno', 1 => 'pql'],
];
Copy after login

After applying the above code, the duplicate values are removed, resulting in:

[
    [0 => 'abc', 1 => 'def'],
    [0 => 'ghi', 1 => 'jkl'],
    [0 => 'mno', 1 => 'pql'],
]
Copy after login

The above is the detailed content of How to Efficiently Remove Duplicate Arrays from a Multi-Dimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template