Home > Net >  Compare 2 similar arrays and remove all similar items in the beginning
Compare 2 similar arrays and remove all similar items in the beginning

Time:09-14

I have 2 similar arrays:

  $array_a = array(
    array(
      "id" => 1,
      "merchant_reference" => "12345"
    ),
    array(
      "id" => 2,
      "merchant_reference" => "67890"
    )
  );

  $array_b = array(
    array(
      "id" => 1,
      "merchant_reference" => "12345"
    ),
    array(
      "id" => 2,
      "merchant_reference" => "67890"
    ),
    array(
      "id" => 3,
      "merchant_reference" => "12345"
    )
  );

The only difference is $array_b has an additional item. I'd like to output a new array that counts the total keys of $array_a and removes all keys in $array_b up to that count. And, just leave the 3rd item in $array_b.

I've tried:

function compare_arrays($array1, $array2) {
    $array1_count = count($array1);
    $array2_count = count($array2);
    $array2_count = $array2_count - $array1_count;
    $array2 = array_slice($array2, $array1_count, $array2_count);

    return $array2;
}

But, what's the best way to do this?

CodePudding user response:

As per the discussion under comment, your code is fine, just an additional conditional check which will improve execution time in case no addition after 12 pm is found.

function compare_arrays($array1, $array2) {
    $array1_count = count($array1);
    $array2_count = count($array2);
    $array2_count = $array2_count - $array1_count;
    if($array2_count > 0){
        return $array2 = array_slice($array2, $array1_count, $array2_count);
    }
    return $array1;
}
  • Related