Home  >  Article  >  Backend Development  >  How to find the intersection of two arrays in PHP

How to find the intersection of two arrays in PHP

青灯夜游
青灯夜游Original
2018-12-29 17:53:2415263browse

In PHP, you can use the built-in function array_intersect() to find the intersection of two arrays, which can return the common elements (intersection part) of the two arrays. Let’s introduce it in detail below.

How to find the intersection of two arrays in PHP

##array_intersect() function

Basic syntax:

array_intersect($ array1,$ array2)

Description: The The function returns an array containing all the values ​​of array1 present in array2.

Note: Since the array_intersect() function takes an array with reserved keys, we also need to use the array_values() function to reorder the keys.

Simple example

Let’s take a look at the array_intersect() function’s method of finding the intersection of two arrays through an example

<?php 
// 定义两个数组
$array1 = array(2, 5, 7, 6, 9); 
$array2 = array(3, 2, 5, 6, 8); 
  
// 找到两个数组的交集
$result = array_intersect($array1, $array2); 
  
// 重新索引
$result = array_values($result); 
  
// 输出结果数组(交集)
var_dump($result); 
?>

Output:


How to find the intersection of two arrays in PHP

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of How to find the intersection of two arrays 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