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

How to find the intersection of two arrays in PHP

青灯夜游
Release: 2023-04-04 15:56:01
Original
15278 people have browsed it

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)
Copy after login

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); 
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template