In this post we will be creating a PHP script that will return the differences between two arrays, here we will be checking for a difference in value and index. And so the script will check if the value and placement of the item via its index are the same.
Arrays in PHP are a means of storing multiple items in to a single a variable. To do this we will be using the ‘array_diff_assoc()’ function which computes the difference of arrays along with an additional check on the index.
See below our two arrays for this example.
$array1 = array("James", "Rahul", "Amy", "Leah");
$array2 = array("James", "Tobi", "Rahul", "Leah");
Using the snippet of code below we utilize the ‘array_diff_asoc()’ function to get the difference between ‘array1’ and ‘array2’.
<?php
$array1 = array("James", "Rahul", "Amy", "Leah");
$array2 = array("James", "Tobi", "Rahul", "Leah");
$difference = array_diff_assoc($array1, $array2);
print_r($difference);
?>
The above would return the following as output. ‘Rahul’ is also returned as the index of this item differs in ‘array2’.
Array ( [1] => Rahul [2] => Amy )