PHP array_diff() Function

PHP array_diff() Function


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP array_diff() Function.

The built-in array_diff() function is used to compare array1 against one or more other arrays that is passed to it and then returns the values in array1 that are not present in any of the other arrays.

Syntax

Following below is the syntax to use this function -

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


Parameter Details

Sr.NoParameter & 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 Value

This built-in PHP function returns an array containing all the entries from input array array1 which are not present in any of the other arrays that is passed to the function.

PHP Version

This function was first lunched as part of core PHP v 4.0.1.

Example1

Try the following example below -

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

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

Output

When the above code is executed, it will produce the following result -

Array 
( 
    [1] => banana 
)

Example2

Multiple occurrences in $array1 are treated the same way. Try the following example -

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

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

Output

When the above code is executed, it will produce the following result -

Array 
( 
    [1] => blue 
)


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the PHP array_diff_assoc() Function.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.