How to calculate the intersection between multiple arrays in PHP? (code example)

藏色散人
Release: 2023-04-05 19:14:02
Original
3174 people have browsed it

This built-in function of PHP array_intersect_key() is used to calculate the intersection of two or more arrays. This function differs from array_intersect() and array_intersect_assoc() in that it uses keys for comparison and returns the matching key element. This function prints only the elements of the first array whose key values ​​match the elements of all other arrays. (Recommended: "PHP Tutorial")

Syntax:

array array_intersect_key($array1, $array2, $array3, $array4...)
Copy after login

Parameters: array_intersect_key() The function accepts at least two array as parameter. It can take any number of arrays, greater than or equal to two arrays separated by commas (', ').

Return type: The function returns another array containing the elements of the first array that are present as parameters in all other arrays, whose key values ​​match each other. If there are no matching keys, an empty array is returned.

Example:

输入: $array1 = ("1" => "aakash", "2" => "rishav", "3" => "gaurav")
        $array2 = ("1" => "shyam", "2" => "rishi", "5" => "rishav")
        $array3 = ("1" => "aakash", "4" => "raghav", "2" => "ravi")
输出:
        Array
        (
          [1] => aakash
          [2] => rishav
        )
Copy after login

The following program demonstrates the array_intersect_key() function. In the following program example, we use array_intersect_key() to find the intersection between arrays.

<?php 
   
$array1 = array("1" => "aakash", "2" => "rishav", "3" => "gaurav"); 
$array2 = array("1" => "shyam", "2" => "rishi", "5" => "rishav"); 
$array3 = array("1" => "aakash", "4" => "raghav", "2" => "ravi"); 
  
print_r(array_intersect_key($array1, $array2, $array3));
Copy after login

Output:

Array
(
    [1] => aakash
    [2] => rishav
)
Copy after login

This article is an introduction to the method of calculating the intersection between multiple arrays in PHP. It is simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of How to calculate the intersection between multiple arrays in PHP? (code example). 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!