Deividas Vysniauskas Deividas Vysniauskas - 1 year ago 68
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
, which would be two Johns and two Davids, but then I'd need to check
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 Source

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:


$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;
            $duplicates[] = $fullname_tmp;
            $duplicates[] = $fullname_tmp;

        $fullname[] = $fullname_tmp;

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


echo "\n full names \n";


The example is using in_array and a simple for loop.

Checkout this DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download