0

I'm trying to match 2 arrays that look like below.

$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

My problem is, I need the array keys of both arrays to be the same value and same count.

Which means:

// passes - both arrays have the same key values and same counts of each key
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

// fails - $public does not have 'blue' => 1
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('red' => 2, 'green' => 3, 'purple' => 4);

// should fail - $public has 2 'blue' => 1 
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);

I've tried using array_diff_keys, array_diff and other php functions, but none can catch extra keys with the same value (i.e. if 'blue' => 1, is repeated it still passes)

What's a good way to solve this?

Norman
  • 6,159
  • 23
  • 88
  • 141
  • 2
    Your last `$public` array is invalid, you can't have two `blue` keys in an array. If you `var_export(array('blue' => 1, 'blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4))` you will get `array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4)` – Nick Feb 19 '19 at 04:53
  • @SougataBose why did you delete your answer it is correct... – Nick Feb 19 '19 at 04:56
  • this problem can't fix by php, this is just how php behave, php gets the last value of distinct key – Beginner Feb 19 '19 at 05:45

1 Answers1

1

When you write two values with same key in PHP, the second one will overwrite the value from the first (and this is not an error). Below is what I did on the PHP interactive CLI (run it with php -a):

php > $x = ["x" => 1, "x" => 2, "y" => 2];
php > var_dump($x);
array(2) {
  ["x"]=>
  int(2)
  ["y"]=>
  int(2)
}

So array_diff seems to be working correctly. You are just expecting PHP to behave in a different way than it actually does!

Vaibhav
  • 628
  • 6
  • 10