• PHP Video Tutorials

PHP array_diff() Function



Definition and Usage

The array_diff() function compares array1 against one or more other arrays passed to it and returns the values in array1 that are not present in any of the other arrays.

Syntax

array array_diff ( array $array1, array $array2 [, array $array3 ...] );

Parameters

Sr.No Parameter & Description
1

array1 (Required)

This is the first array which will be compared with other arrays passed to the function.

2

array2 (Required)

This is an array to be compared with the first array

3

array3 (Optional)

This is the second array to be compared with the first array

4

More Arrays (Optional)

You can pass more number of arrays you want to compare with the first input array.

Return Values

The PHP function array_diff() returns an array containing all the entries from input array array1 which which are not present in any of the other arrays passed to the function.

PHP Version

This function was first introduced in PHP Version 4.0.1.

Example

Try out following example −

<?php
   $array1 = array("orange", "banana", "apple");
   $array2 = array("orange", "mango", "apple");

   print_r(array_diff($array1, $array2));
?>

This will produce the following result −

Array 
( 
    [1] => banana 
)

Example

Multiple occurrences in $array1 are all treated the same way. Try out following example −

<?php
   $array1 = array("a" => "green", "red", "blue", "red");
   $array2 = array("b" => "green", "yellow", "red");

   print_r(array_diff($array1, $array2));
?>

This will produce the following result −

Array 
( 
    [1] => blue 
)
php_function_reference.htm
Advertisements