php compare two arrays code example

Example 1: php find differences between two arrays

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Array
(
    [1] => blue
)

Example 2: php merge 2 arrays

<?php
  $array1 = [
      "color" => "green"
  ];
  $array2 = [
      "color" => "red", 
      "color" => "blue"
  ];
  $result = array_merge($array1, $array2);
?>

// $result
[
    "color" => "green"
    "color" => "red", 
    "color" => "blue"
]

Example 3: array_diff

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
?>

Array
(
    [1] => blue
)

Example 4: array_diff php

<?php
$arr_1 = array("a" => "car", "b" => "plane", "c" => "boat", "d" => "bike");
$arr_2 = array("e" => "car", "f" => "plane", "g" => "boat");

$result = array_diff($arr_1, $arr_2);
print_r($result);

/* Result:
Array
(
    [d] => bike
)
 */

Tags:

Php Example