Theonly
Theonly

Reputation: 59

Check if a value has duplicate and the other column is different in a multidimensional array in php?

I have multidimensional array like this.

array:8 [
  0 => array:8 [
    "SERIAL" => "qwerty"
    "BRANCH" => "TEST1"
  ]
  1 => array:8 [
    "SERIAL" => "qwer"
    "BRANCH" => "TEST1"
  ]
  2 => array:8 [   // RETURN THIS AS ERROR AS THE BRANCH "TEST1" has already "qwerty" serial
    "SERIAL" => "qwerty"
    "BRANCH" => "TEST2"
  ]
  3 => array:8 [   
    "SERIAL" => "qwerty"
    "BRANCH" => "TEST1"
  ]
]

My goal is to return error if there is a duplicate value of "SERIAL" and different "BRANCH".

Any idea how to achieve this?

Upvotes: 1

Views: 69

Answers (3)

Progrock
Progrock

Reputation: 7485

You could sort the array (here a copy) by SERIAL, and then if you have the same SERIAL values, check to see if they lie on different BRANCHs.

<?php
$dupes = false;
usort($result = $data, function($a, $b) use (&$dupes) {
    $out = $a['SERIAL'] <=> $b['SERIAL'];
    if($out === 0 && $a['BRANCH'] !== $b['BRANCH'])
        $dupes = true;

    return $out;
});

var_dump($dupes);

Output:

bool(true)

Upvotes: 1

Andreas
Andreas

Reputation: 23958

If you group the serials and branches then you can see if the unique count is more than one.
This will output all the duplicates not just the first.

foreach($arr as $sub){
    $result[$sub['SERIAL']][] = $sub['BRANCH'];
}

foreach($result as $serial => $branches){
    $unique = array_unique($branches);
    if(count($unique) >1){
        var_dump("ERROR: " . $serial, array_slice($unique,1));
    }
}

Output:

string(13) "ERROR: qwerty"
array(2) {
  [0]=>
  string(5) "TEST2"
  [1]=>
  string(5) "TEST3" // I added that to test on multiple duplicates
}

https://3v4l.org/Qj98N

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163297

One option could be using 2 foreach loops and check if SERIAL is the same and BRANCH is different.

If that is the case, break out of the loops or handle it accordingly.

foreach ($arrays as $arrayA) {
    foreach ($arrays as $arrayB) {
        if ($arrayA["SERIAL"] == $arrayB["SERIAL"] && $arrayA["BRANCH"] !== $arrayB["BRANCH"]) {
            print_r($arrayB);
            break 2;
        }
    }
}

See a php demo

Upvotes: 1

Related Questions