-1

I have two arrays, the first is below:

Array
(
    [0] => 21-02
    [1] => 21-01
    [2] => 21-03
    [3] => 21-04
    [4] => 21-05
    [5] => 21-06
    [6] => 21-07
    [7] => 21-08
    [8] => 21-09
)

I need to check what values don't exist in this second array:

Array
(
    [0] => 21-01
    [1] => 21-02
)

If they don't exist in the second array then I need to add them. How can I do that?

Rob
  • 6,304
  • 24
  • 83
  • 189
  • Can you show the resulting array you need at the end from the above 2 array in the example? – Ajith Oct 13 '21 at 12:40
  • Does this answer your question? [add to array if it isn't there already](https://stackoverflow.com/questions/6083567/add-to-array-if-it-isnt-there-already) – Cray Oct 13 '21 at 12:41

1 Answers1

2

You can achieve this with array_diff().

$valuesThatAreNotInArray2 = array_diff($array1, $array2);

After you have the differences between the first array and the second array you can merge the differences with the second array.

$array2 = array_merge($array2, $valuesThatAreNotInArray2);
Marcel
  • 4,854
  • 1
  • 14
  • 24