PHP array_diff() function
In this chapter you will learn:
- Syntax for PHP array_diff() function
- Description for PHP array_diff() function
- Parameter for PHP array_diff() function
- Example - Find the difference between two arrays
- Example - Different two associative arrays
Syntax
PHP array_diff() function has the following syntax
array array_diff ( array arr1, array arr2 [, array ...] )
Description
The array_diff() function returns a new array containing all the values of array $arr1 that do not exist in array $arr2.
You can diff several arrays by providing more parameters. The function will return an array of values in the first array that do not appear in the second and subsequent arrays.
For example:
$arr1_unique = array_diff($array1, $array2, $array3, $array4);
Parameter
Parameter | Is required | Description |
---|---|---|
array1 | Required. | The array to compare from |
array2 | Required. | An array to compare against |
array3,... | Optional. | More arrays to compare against |
Example 1
Find the difference between two arrays
<?PHP//from j av a 2 s .c o m
$toppings1 = array("A", "B", "C", "D");
$toppings2 = array("C", "D", "java2s.com");
$diff_toppings = array_diff($toppings1, $toppings2);
var_dump($diff_toppings);
?>
The code above generates the following result.
Example 2
Different two associative arrays
<?php//from j a v a2s.co m
$a1=array("a"=>"A","b"=>"B","c"=>"C","j"=>"java2s.com");
$a2=array("e"=>"E","f"=>"F","g"=>"Good");
$a3=array("a"=>"Apple","b"=>"New B","h"=>"Help");
$result=array_diff($a1,$a2,$a3);
print_r($result);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Description for PHP array_diff_assoc() Function
- Syntax for PHP array_diff_assoc() Function
- Parameter for PHP array_diff_assoc() Function
- Example - Compare the keys and values of two arrays, and return the differences
- Example - Compare the keys and values of three arrays, and return the differences
Home » PHP Tutorial » PHP Array Functions