PHP's array_diff Function
The array_diff function in PHP is a built-in function that is used to compare arrays and return the values that are present in one array but not in another. This function is particularly useful when you need to find the difference between two arrays, such as in cases when you want to compare data in a database against a list of values that have been entered into a form.
How array_diff Works
The array_diff function compares two or more arrays and returns an array containing the values that are present in the first array but not in any of the subsequent arrays. The comparison is strictly value-based (keys are ignored). If a value from the first array is not found in the other arrays, it is added to the result.
Syntax
The syntax for the array_diff function is as follows:
PHP array_diff function syntax
array array_diff (array $array1, array $array2 [, array $... ]);The array1 parameter is the first array that you want to compare. The array2 parameter is the second array that you want to compare against. You can also include additional arrays by adding more parameters.
Examples
Let's take a look at a few examples of how you can use the array_diff function in your PHP code.
PHP example of array_diff function usage
<?php
$array1 = [1, 2, 3];
$array2 = [2, 3, 4];
$result = array_diff($array1, $array2);
print_r($result);
?>This code will output the following:
Array ( [0] => 1 )As you can see, the array_diff function has returned the value of 1, which is present in $array1 but not in $array2. Note that array_diff preserves the original keys from the first array.
PHP example with string values (case sensitivity)
<?php
$array1 = ['apple', 'Banana', 'cherry'];
$array2 = ['apple', 'banana', 'date'];
$result = array_diff($array1, $array2);
print_r($result);
?>This code will output the following:
Array ( [1] => Banana )In this example, string comparison is case-sensitive. Since 'Banana' does not exactly match 'banana', it is returned as a difference.
Conclusion
The array_diff function is a useful tool for comparing arrays and finding the differences between them. Whether you're working with data from a database, or simply comparing lists of values, the array_diff function can help you quickly and easily find the values that are unique to one array. By using this function in your PHP code, you can streamline your development process and make it easier to find and process the data that you need.
Practice
What does the array_diff() function in PHP do?