简体   繁体   中英

Comparing two arrays using both keys and values

Hello i have two arrays one coming from the client and the other coming from my database, i want to be able to compare these two arrays and make sure they are both equal.

By equal i mean they both have the same keys and the keys have the same values:

array (size=2)
  0 => 
    array (size=5)
      'id' => int 13
      'class' => string 'Regular' (length=7)
      'price' => int 100
  1 => 
    array (size=5)
      'id' => int 13
      'class' => string 'Regular' (length=7)
      'price' => int 200


array (size=2)
  0 => 
    array (size=5)
      'id' => int 13
      'class' => string 'Regular' (length=7)
      'price' => int 100
  1 => 
    array (size=5)
      'id' => int 13
      'class' => string 'Regular' (length=7)
      'price' => int 300

In the above scenario y function shuld return false because even though my arrays have the same number of elements the price property of the second index is different, first array has 200 ad second array has 300.

Also if for some reason array 1 has more elements than array 2 then it should also return false.

What would be the best way of doing this? Bets in terms of speed and performance.

I was thinking of converting both arrays to json and checking them like a string.

Try this

$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

array_diff() is there for this purpose. And its ok if the arrays are small, but for optimization, check out this post . It involves flipping the array value and key for faster comparison. And also this other stack comment for a hash table approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM