Home  >  Article  >  Backend Development  >  How to determine if two arrays have the same value in php

How to determine if two arrays have the same value in php

PHPz
PHPzOriginal
2023-04-25 09:05:41840browse

In Php, it is very simple to determine whether two arrays have the same value. You can use the array_intersect() function. This function is used to obtain the common elements of two or more arrays and return a new array, where Contains elements from the original array that are present in all parameter arrays.

The syntax is as follows:

array_intersect( array $array1 , array $array2 [, array $... ] ) : array

This function receives two or more arrays as parameters and returns an array containing common elements in all parameter arrays. Among them,

  • array1: required. The first array.
  • array2: Required. The second array compared to the first array.
  • array: optional. Additional arrays to be used with the first array.

Next, we use a simple example to demonstrate how to use this function to determine whether there are the same values ​​​​in two arrays:

//定义两个数组
$arr1 = array("apple", "banana", "orange");
$arr2 = array("peach", "pear", "apple");

//获取两个数组的交集
$common = array_intersect($arr1, $arr2);

//输出结果:Array ( [0] => apple )
var_dump($common);

In the above code, we define two The arrays $arr1 and $arr2 contain different string elements respectively. By calling the array_intersect() function, the common elements in the two arrays are obtained. The result is "apple" because "apple" is the only element contained in both arrays.

Not only that, we can also use multiple array parameters in this function. For example:

//定义三个数组
$arr1 = array("apple", "banana", "orange");
$arr2 = array("peach", "pear", "apple");
$arr3 = array("orange", "kiwi");

//获取三个数组的交集
$common = array_intersect($arr1, $arr2, $arr3);

//输出结果:Array ( [0] => apple [1] => orange )
var_dump($common);

In the above code, we define three arrays $arr1, $arr2 and $arr3, each containing different string elements. By calling the array_intersect() function, the common elements in these three arrays are obtained. The results obtained are "apple" and "orange" because these two elements are included in the three arrays.

Therefore, using the array_intersect() function can easily filter out the same values ​​​​in two or more arrays, providing very practical functions for array operations.

The above is the detailed content of How to determine if two arrays have the same value in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn