Web Development & WordPress

Understanding Array Differentiation in PHP

Here I will try to show about how to find different elements between arrays using array_diff and array_diff_assoc functions in PHP. This will help you to understand array differentiation based on values and keys.

<?php
echo "<pre>";
$arr1 = array(1, 3, 22, 3, 5, 8, 6, 4, 12, 19, 15);
$arr2 = array(2, 6, 4, 9, 7, 8, 12, 22, 44, 23, 15);

$diffElements = array_diff($arr1, $arr2);
echo "Different Elements of Array based on values and not by keys:<br><br>";
print_r($diffElements);

$diffElements = array_diff_assoc($arr1, $arr2);
echo "Diffrent Elements of Array based on Keys and Values:<br><br>";
print_r($diffElements);

$arr3 = array("a" => "Tom", "c" => "Jim", "e" => "Harry");
$arr4 = array("j" => "Jim", "k" => "Julia", "m" => "Robin");

$diffElements = array_diff($arr3, $arr4);
echo "Different Elements of Array based on values and not by keys:<br><br>";
print_r($diffElements);

$arr3 = array("a" => "Rebecca", "d" => "Jim", "e" => "Henry");
$arr4 = array("d" => "Jim", "k" => "June", "m" => "Maddy");
$diffElements = array_diff_assoc($arr3, $arr4);
echo "Different Elements of Array based on Keys and Values:<br><br>";
print_r($diffElements);

echo "</pre>";
?>

OUTPUT:

Different Elements of Array based on values and not by keys:

Array
(
    [0] => 1
    [1] => 3
    [3] => 3
    [4] => 5
    [9] => 19
)
Diffrent Elements of Array based on Keys and Values:

Array
(
    [0] => 1
    [1] => 3
    [2] => 22
    [3] => 3
    [4] => 5
    [6] => 6
    [7] => 4
    [8] => 12
    [9] => 19
)
Different Elements of Array based on values and not by keys:

Array
(
    [a] => Tom
    [e] => Harry
)
Different Elements of Array based on Keys and Values:

Array
(
    [a] => Rebecca
    [e] => Henry
)

Leave a comment