The array function array_diff() in PHP compares the values of two or more arrays and returns the differences between them. The function returns an array from the first array with values that are not present in the second array or more arrays that come next.

This function was introduced in PHP version 4.0.1 and it is still present in PHP version 7.

Syntax of array_diff function

array_diff(array1, array2, array3, ..., arrayN)

PHP Manual Reference: https://www.php.net/manual/en/function.array-diff.php

How to use this function?

Create two indexed array Subject 1 and Subject 2 as below:

$aSubject1 = array("PHP", "Ajax", "jQuery", "CSS", "jSon");$aSubject2 = array("PHP", "Ajax", "jQuery");

$aSubject3 = array("Mysql", "Javascript", "jSon");$aDifferenceArray = array_diff($aSubject1,$aSubject2,$aSubject3); Output: ( [3] => CSS ) How to use this function in a multidimensional array? $aSubject1 = array(
array('subject'=>"PHP"),
array('subject'=>"Ajax"),
array('subject'=>"jQuery"),
array('subject'=>"CSS"),
array('subject'=>"jSon")
);

$aSubject2 = array( array('subject'=>"PHP"), array('subject'=>"Ajax"), array('subject'=>"jQuery") );$aDifferenceArray = array_diff($aSubject1,$aSubject2);

Output:

(
)

In the above case, the function returns a blank array. This function only checks the values of two arrays and returns the difference. But in a multidimensional array, it cannot find the values.

So, we have to find the values between two arrays, and then apply the array_diff() function. Let us define two variables of an array data type.

$aVal1 = array();$aVal2 = array();

foreach($aSubject1 as$aSubject)
{
$aVal1[] =$aSubject["'subject'"];
}

This code will fetch all the values of array $aSubject1 and store into the array $aVal1. The same code will be applied to $aSubject2. foreach($aSubject2 as $aSubject) {$aVal2[] = $aSubject["'subject'"]; } Now apply the array_diff() function with two parameters $aVal1 and $aVal1. $aDifferenceArray = array_diff($aVal1,$aVal2);

Output:

Array
(
[3] => CSS
[4] => jSon
)

Watch Video