Home  >  Article  >  Backend Development  >  How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?

How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 22:22:10946browse

How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?

PHP Multidimensional Array: Removing Duplicates Based on Email

Problem:

You have a multidimensional array with subarrays containing name, surname, and email information, as shown below:

$array = [
    [0] => ['dave', 'jones', 'dave.jones@example.com'],
    [1] => ['john', 'jones', 'john.jones@example.com'],
    [2] => ['bruce', 'finkle', 'bruce.finkle@example.com'],
];

You need to remove duplicate subarrays based on the email value.

Solution:

To effectively deduplicate a multidimensional array based on a specific value, we can utilize array indexes' uniqueness. Here's a solution using this approach:

$newArr = [];
foreach ($array as $val) {
    $newArr[$val[2]] = $val;    
}
$array = array_values($newArr);

Notice:

  • The last match for each email address is retained in the resulting array. To prioritize the first match, reverse the array before iterating through it:
foreach (array_reverse($array) as $val) {
  • The array indexes in the new array may not be consecutive.

The above is the detailed content of How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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