Home »
PHP
PHP Array array_diff() Function (With Examples)
In this tutorial, we will learn about the PHP array_diff() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP array_diff() Function
The array_diff() function is an array function in PHP, it is used to find the differences of two or more arrays.
It compares the values of given arrays and returns the values which are not common in the arrays.
It compares values of the first array with the second array and returns the values which are not present in the second array.
Syntax
The syntax of the array_diff() function:
array_diff(array1, array2, ...) : array
Parameters
The parameters of the array_diff() function:
- array1, array2 are the input arrays, two array parameters are required. We can also provide more arrays to compare.
Return Value
The return type of this method is array, it returns an array containing all the entries from array that are not present in any of the other arrays. Keys in the array array are preserved. [Source]
Sample Input/Output
Input:
$arr1 = array("101" => "Amit", "102" => "Abhishek", "103" => "Prem");
$arr2 = array("101" => "Amit", "102" => "Abhishek");
Function call:
array_diff($arr1, $arr2);
Output:
Array
(
[103] => Prem
)
PHP array_diff() Function Example 1
<?php
$arr1 = array("101" => "Amit", "102" => "Abhishek", "103" => "Prem");
$arr2 = array("101" => "Amit", "102" => "Abhishek");
//finding & printing arrays
$ans = array_diff($arr1, $arr2);
print_r ($ans);
?>
Output
The output of the above example is:
Array
(
[103] => Prem
)
PHP array_diff() Function Example 2
<?php
$arr1 = array(10, 20, 30, 40, 50);
$arr2 = array(10, 20, 60, 70, 70);
print_r (array_diff($arr1, $arr2));
?>
Output
The output of the above example is:
(
[2] => 30
[3] => 40
[4] => 50
)
To understand the above example, you should have the basic knowledge of the following PHP topics: