Home > Backend Development > PHP Tutorial > How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

Barbara Streisand
Release: 2024-11-25 09:34:10
Original
432 people have browsed it

How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

Removing Duplicates from Multi-Dimensional PHP Arrays

In PHP, working with multi-dimensional arrays often involves the need to eliminate duplicate elements. This can be particularly useful when dealing with large datasets where identical values may appear in multiple sub-arrays.

Consider the following example, where we have a 2D array with sub-arrays containing name, email, and other information:

$array = [
    [
        'name' => 'Dave',
        'email' => 'dave@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Bruce',
        'email' => 'bruce@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
];
Copy after login

In this example, we have a duplicate entry with the same email address ('john@example.com'). To remove the duplicate sub-array, we can utilize the uniqueness of array indexes using the following snippet:

$newArr = [];
foreach ($array as $val) {
    $newArr[$val['email']] = $val; 
}
$array = array_values($newArr);
Copy after login

By iterating through the sub-arrays and using the email address as the key for the new array, we overwrite any duplicate values with the last matching sub-array. The array_values() function is then used to reset the array indexes, resulting in a deduplicated array:

$array = [
    [
        'name' => 'Dave',
        'email' => 'dave@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Bruce',
        'email' => 'bruce@example.com',
    ],
];
Copy after login

This technique effectively removes duplicate values based on the specified key, leaving us with a deduplicated multi-dimensional array.

The above is the detailed content of How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?. 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