Tutorialspoint.dev

PHP | array_diff() function

The array_diff() is an inbuilt function in PHP ans is used to calculate the difference between two or more arrays. This function computes difference according to the values of the elements, between one or more array and return differences in the form of a new array. This function basically returns all the entries that are present in the first array which are not present in any other arrays.

Syntax:

array_diff($array1, $array2, $array3, ...,$arrayn)

Parameters: The function can take any number of arrays as parameters needed to be compared.

Return Type: This function compares the first array in parameters with rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays.

Examples:



Input :  $array1 = ('a', 'b', 'c');
         $array2 = ('a', 'd', 'e');
         $array3 = ('a', 'b', 'f');
         array_diff($array1, $array2, $array3); 
Output :
         Array
         (
           [2] => c
         )

Input : $array1 = ('a', 'b', 'a');
        $array2 = ('a', 'd', 'e');
Output :
         Array
         (
           [1] => b
         )

Below program illustrates the working of array_diff() in PHP:

<?php
// PHP code to illustrate the working of array_diff()
function Difference($array1, $array2, $array3){
    return(array_diff($array1, $array2, $array3));
}
  
// Driver Code
$array1 = array('a', 'b', 'c', 'd', 'e', 'f');
$array2 = array('a', 'b', 'g', 'h');
$array3 = array('a', 'f', 'i');
print_r(Difference($array1, $array2, $array3));
?>

Output:

Array
(
    [2] => c
    [3] => d
    [4] => e
)

Important points to note:

  • It compares the elements in their string representation. That is, 1 and ‘1’ are both equal for array_diff().
  • The number of repetition of element in first array doesn’t matter. That is if an element occurs 3 times in $array1 and only 1 time in other arrays then all of the 3 occurrences of that element in first array will be omitted in output.
  • For multi-dimensional arrays, we need to to compare each of the dimensions separately. For example:- $array1[2],$array2[2] etc.

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



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter