Hướng dẫn
Quảng cáo

Hàm array_intersect() trong PHP

Hướng dẫn cách sử dụng hàm array_intersect() về mảng trong lập trình PHP

Tác dụng của hàm array_intersect()

The array_intersect() function compares the values of two or more arrays and returns the matches. The keys are not considered in the comparison, only the values are checked.

The following table summarizes the technical details of this function.

Return Value: Returns an array containing all the elements from array1 whose values are present in all of the other arrays.
Version: PHP 4.0.1+

Syntax

The basic syntax of the array_intersect() function is given with:

array_intersect(array1, array2, ...);

The following example shows the array_intersect() function in action.

<?php
// Sample arrays
$array1 = array("apple", "ball", "cat", "dog", "elephant");
$array2 = array("alligator", "dog", "elephant", "lion", "cat");

// Computing the intersection
$result = array_intersect($array1, $array2);
print_r($result);
?>

Parameters

The array_intersect() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array to compare from.
array2 Required. Specifies an array to compare against.
... Optional. Specifies more arrays to compare against.

More Examples

Here're some more examples showing how array_intersect() function actually works:

The following example shows how to use this function to compare an array against two other arrays.

<?php
// Sample arrays
$array1 = array("apple", "ball", "cat", "dog");
$array2 = array("cat", "lion", "tiger");
$array3 = array("parrot", "cat");

// Computing the intersection
$result = array_intersect($array1, $array2, $array3);
print_r($result);
?>

Two elements are considered equal if their string representation are same, i.e., (string) $elem1 === (string) $elem2. Let's take a look at the following example:

<?php
// Sample arrays
$array1 = array(1, 2, 5, 7, 11);
$array2 = array(0, "1", 2, 4, "07", 10);

// Computing the intersection
$result = array_intersect($array1, $array2);
print_r($result);
?>

You can also use associative arrays, however the keys are not considered in the comparison.

<?php
// Sample arrays
$array1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$array2 = array("x"=>"black", "y"=>"blue", "z"=>"red");

// Computing the intersection
$result = array_intersect($array1, $array2);
print_r($result);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements