> 文章列表 > php array_diff

php array_diff

php array_diff

Introduction

PHP is a widely used server-side scripting language that provides a vast array of functions to perform various tasks efficiently. One of the essential functions provided by PHP is `array_diff()`, which allows us to compare two or more arrays and return the difference between them. In this article, we will explore this function in detail and learn how to use it in practical scenarios.

What is array_diff()?

`array_diff()` is a built-in PHP function that compares two or more arrays and returns the values from the first array that are not present in the rest of the arrays. In other words, it returns an array containing all the elements from the first array that are not present in any of the other arrays provided.

How to use array_diff()?

The syntax of `array_diff()` is straightforward:
array_diff(array1,array2,array3,...);
Where array1 is the primary array to compare, and array2,array3,...are the additional arrays to compare. The function returns an array containing all the elements from the first array that are not present in any of the other arrays provided. Let’s look at some examples to understand this function better.

Examples

Suppose we have two arrays:
$arr1 = array(3, 7, 9, 11, 15);
$arr2 = array(1, 5, 7, 9, 11);
Using `array_diff()`, we can find out the difference between these two arrays. Here’s how we can use the function:
$result = array_diff($arr1, $arr2);After executing this code, `$result` will hold an array containing the values 3 and 15, which are not present in `$arr2`.Similarly, if we have three arrays `$arr1`, `$arr2`, and `$arr3`, we can find out the difference between them by passing all of these arrays to the `array_diff()` function. Here’s how we can do that:
$result = array_diff($arr1, $arr2, $arr3);

Conclusion

In summary, `array_diff()` is a powerful PHP function that allows us to compare two or more arrays and return the difference between them. By using this function, we can quickly determine the elements that are unique to a particular array and perform various data manipulation tasks in our PHP applications.