PHP array_​diff_​assoc Function



array_​diff_​assoc() is an another PHP prebuilt / default array function, This function is basically allows user to compare the values of two arrays, and return the differences. array_​diff_​assoc function compares the values of two (or more) arrays, and return an array that contains the entries from first array that are not present in second or third array, etc. This function basically returns all the entries that are present in the first array which are not present in any other arrays.

Syntax of array_​diff_​assoc() :

array_​diff_​assoc($array_1, $array_2, $array_3, …)

Parameter :
array_1 (required) : Opertatonal array to compare from
array_2 (required) : Array to compare against
array_3 (optional) : More arrays to compare against

Return Type / Values : Returns an array containing the entries from array_1 that are not present in any of the other arrays

Example 1 :

<?php
	$array_1 = array('a', 'b', 'c', 'd');
	$array_2 = array('b', 'd', 'f');
	$result = array_diff($array_1, $array_2);
	print_r($result);
?>

Output will be :

Array 
	( 
		[0] => a 
		[2] => c 
	)

If you can see in first array on first position a is missing in second array and on 3rd position c is missing from array_2.

Example 2 : Get column of last names from a record set, indexed by the “userId” column:

<?php
// array_diff() function

function differences($array_1, $array_2, $array_3){
    return(array_diff($array_1, $array_2, $array_3));
}
  
$array_1 = array('aa', 'bb', 'cc', 'dd', 'ee', 'ff');
$array_2 = array('aa', 'bb', 'xx', 'yy');
$array_3 = array('aa', 'xx', 'yy');
print_r(differences($array_1, $array_2, $array_3));

?>

Output will be :

Array 
	( 
		[2] => cc 
		[3] => dd 
		[4] => ee 
		[5] => ff 
	)

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