Deividas Vysniauskas Deividas Vysniauskas - 3 months ago 12
PHP Question

PHP: Checking two arrays for duplicate values

I have two arrays, one that contains a persons first name and another one that contains a persons last name.

$firstname = array ( "John", "Tom", "Ben", "John", "David", "Julie", "David");
$lastname = array ( "Kennedy", "Hyde", "Hughes", "Harper" "Walter", "Weber", "Walter");


A persons first and last names are in both arrays with the same index ( John Kennedy, Tom Hyde, etc.) And I'm searching for a way to find duplicate values in the array
$firstname
, which would be two Johns and two Davids, but then I'd need to check
$lastname
with the same indexes if they are duplicate too, so the output would be
David Harper, David Harper
.

The array can contain around 50+ different names and last names.

Couldn't find anything on the internet and I'm running out of ideas, any help would be greatly appreciated.

Answer

You have to make a third array that handles the resultant value i.e the full name. The following example will return two arrays, duplicates array and fullnames array without duplicates:

    <?php

$firstname = array ( "John", "Tom", "Ben", "John", "David", "Julie", "David");
$lastname = array ("Kennedy", "Hyde", "Hughes", "Harper", "Walter", "Weber", "Walter");
$fullname = array();
$duplicates = array();

// foreach time we have a first name.
for ($i =0; $i < count($firstname); $i++){
    $fullname_tmp = $firstname[$i]." ".$lastname[$i];
    if (in_array($fullname_tmp, $fullname)){
        if (in_array($fullname_tmp, $duplicates)){
            $duplicates[] = $fullname_tmp;
        }
        else{
            $duplicates[] = $fullname_tmp;
            $duplicates[] = $fullname_tmp;
        }

    }
    else{
        $fullname[] = $fullname_tmp;
    }
}

echo "<pre>\n duplicates \n";

print_r($duplicates);

echo "\n full names \n";

print_r($fullname);

The example is using in_array and a simple for loop.

Checkout this DEMO

Comments