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?

3
  • 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) Commented Feb 19, 2019 at 4:53
  • @SougataBose why did you delete your answer it is correct... Commented Feb 19, 2019 at 4:56
  • this problem can't fix by php, this is just how php behave, php gets the last value of distinct key Commented Feb 19, 2019 at 5:45

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.