Tuesday, October 20, 2020

PHP array_diff() Function



Hello folks! welcome to another section of our tutorial on PHP. In this tutorial, we will be discussing about PHP array_diff() Function.

The PHP's array_diff() function compares 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 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 all treated the same way. Try out 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 rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the PHP array_diff_assoc() Function.

Feel free to ask your questions where necessary and i 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.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.