Array Subtraction On PHP

We can use array_diff command on PHP to subtract two array. We use it because we need an unique item between the array. By subtracting the value, we can avoid the duplication on the new array. Here is for example :

  1. <?php
  2. $a = ['Apple', 'Banana', 'Cherry', 'Dragonfruit', 'Elderberry', 'Grape', 'Lemon', 'Mango', 'Orange', 'Peach', 'Raspberry', 'Strawberry', 'Watermelon'] ;
  3. $b = ['Cherry', 'Grape', 'Strawberry'] ;
  4.  
  5. var_dump(array_diff($a,$b));
  6. echo '<br/>';
  7. var_dump(array_diff($b,$a));

For array_diff($a,$b), here is the result :

array(10) { [0] => string(5) “Apple” [1] => string(6) “Banana” [3] => string(11) “Dragonfruit” [4] => string(10) “Elderberry” [6] => string(5) “Lemon” [7] => string(5) “Mango” [8] => string(6) “Orange” [9] => string(5) “Peach” [10] => string(9) “Raspberry” [12] => string(10) “Watermelon” }

From the above, all the values in $b array is same with the $a array. So all remaining value just from $a.

For array_diff($b,$a), here is the result :

array(0) { }

So there is no result (empty array) because all the values in $b array is same with the $a array.

For this case, where $c array has a different value, ‘Pineapple’.

  1. <?php
  2. $a = ['Apple', 'Banana', 'Cherry', 'Dragonfruit', 'Elderberry', 'Grape', 'Lemon', 'Mango', 'Orange', 'Peach', 'Raspberry', 'Strawberry', 'Watermelon'] ;
  3. $c = ['Banana', 'Grape', 'Pineapple'] ;
  4.  
  5. var_dump(array_diff($a,$c));
  6. echo '<br/>';
  7. var_dump(array_diff($c,$a));

Here is the result for array_diff($a,$c).

array(11) { [0] => string(5) “Apple” [2] => string(6) “Cherry” [3] => string(11) “Dragonfruit” [4] => string(10) “Elderberry” [6] => string(5) “Lemon” [7] => string(5) “Mango” [8] => string(6) “Orange” [9] => string(5) “Peach” [10] => string(9) “Raspberry” [11] => string(10) “Strawberry” [12] => string(10) “Watermelon” }

Here is the result for array_diff($c,$a).

array(1) { [2] => string(9) “Pineapple” }

For the case, where $d array has all different value with $a.

  1. <?php
  2. $a = ['Apple', 'Banana', 'Cherry', 'Dragonfruit', 'Elderberry', 'Grape', 'Lemon', 'Mango', 'Orange', 'Peach', 'Raspberry', 'Strawberry', 'Watermelon'] ;
  3. $d = ['Durian', 'Date', 'Pineapple'] ;
  4.  
  5. var_dump(array_diff($a,$d));
  6. echo '<br/>';
  7. var_dump(array_diff($d,$a));
  8.  
  9. ?>

Here is the result for array_diff($a,$d).

array(13) { [0] => string(5) “Apple” [1] => string(6) “Banana” [2] => string(6) “Cherry” [3] => string(11) “Dragonfruit” [4] => string(10) “Elderberry” [5] => string(5) “Grape” [6] => string(5) “Lemon” [7] => string(5) “Mango” [8] => string(6) “Orange” [9] => string(5) “Peach” [10] => string(9) “Raspberry” [11] => string(10) “Strawberry” [12] => string(10) “Watermelon” }

Here is the result for array_diff($d,$a).

array(3) { [0] => string(6) “Durian” [1] => string(4) “Date” [2] => string(9) “Pineapple” }