Home > Software engineering >  Add missing values to second array
Add missing values to second array

Time:10-13

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?

CodePudding user response:

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);

CodePudding user response:

simply :

$array2 = array_merge($array2,array_diff($array1,$array2));
  •  Tags:  
  • php
  • Related