0

I'd like to check, whether an array has been changed compared to another array.

I'd like to get a boolean value for

  1. has changed (true)
  2. has not changed (false)

Let's assume this is my original array:

$originalArray = [1,2,3,];

Now the boolean should be true, if the $newArray looks e.g. like:

Added item

$newArray = [1,2,3,4];

Removed item

$newArray = [1,2];

Different values

$newArray = [1,3,5];

My attempts

$originalArray = [1,2,3,];
$newArray = [1,2,3,4];
array_diff($newArray, $originalArray);

This works fine and the result is

[3 => 4,]

but for

<?php
  
$originalArray = [1,2,3,];
$newArray = [1,2,];
array_diff($newArray, $originalArray);

it does no longer work. I would have to switch $newArray and $originalArray in array_diff.

I think doing something like

$result = count(array_diff($originalArray, $newArray)) === 0 && count(array_diff($newArray, $originalArray)) === 0;

is not the best try?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
SPQRInc
  • 162
  • 4
  • 23
  • 64
  • I don't understand the problem. `array_diff($newArray, $originalArray)` returns the added elements, `array_diff($originalArray, $newArray)` returns the removed elements. – Barmar Sep 17 '21 at 19:35
  • Okay, so my attempt at the end is not the worst idea? – SPQRInc Sep 17 '21 at 19:36
  • 2
    If you just want to know if it has changed, just use `$originalArray == $newArray` – Barmar Sep 17 '21 at 19:37
  • 1
    But if the order is allowed to change, you can use `count(array_intersect($newArray, $originalArray)) == count($originalArray)` – Barmar Sep 17 '21 at 19:38
  • Does this answer your question? [PHP - Check if two arrays are equal](https://stackoverflow.com/questions/5678959/php-check-if-two-arrays-are-equal) – Tangentially Perpendicular Sep 17 '21 at 22:25

0 Answers0