Hướng dẫn dùng intersection array trong PHP

Định nghĩa hàm array_intersect[] trong PHP

__Hàm array_intersect[] trong PHP__ trả về một mảng chứa tất cả value của mảng array1 mà không có mặt trong tất cả tham số. Ghi chú rằng key được giữ nguyên.

Cú pháp hàm array_intersect[] trong PHP

Hàm array_intersect[] trong PHP có cú pháp như sau:

array array_intersect [ array $array1, array $array2 [, array $array3 ...] ];

Tham số

  • array1:Bắt buộc. Mảng nguồn để mảng khác so sánh với
  • array2:Bắt buộc. Một mảng để được so sánh với mảng nguồn
  • array3:Tùy ý. Một mảng để được so sánh với mảng nguồn

Trả về giá trị

Trả về mảng chứa tất cả đầu vào của mảng array1 mà không có mặt trong tất cả mảng khác.

Ví dụ minh họa cách sử dụng hàm array_intersect[] trong PHP:

 

Lưu chương trình trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ //localhost:8080/test.php sẽ cho kết quả:

Xem thêm Hàm trong php

[PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8]

array_intersectComputes the intersection of arrays

Description

array_intersect[array $array, array ...$arrays]: array

Parameters

array

The array with master values to check.

arrays

Arrays to compare values against.

Return Values

Returns an array containing all of the values in array whose values exist in all of the parameters.

Changelog

VersionDescription
8.0.0 This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Examples

Example #1 array_intersect[] example

The above example will output:

Array
[
    [a] => green
    [0] => red
]

Notes

Note: Two elements are considered equal if and only if [string] $elem1 === [string] $elem2. In words: when the string representation is the same.

See Also

  • array_intersect_assoc[] - Computes the intersection of arrays with additional index check
  • array_diff[] - Computes the difference of arrays
  • array_diff_assoc[] - Computes the difference of arrays with additional index check

stuart at horuskol dot co dot uk

14 years ago

A clearer example of the key preservation of this function:



yields the following:

array[3] {
  [0]=> int[2]
  [1]=> int[4]
  [2]=> int[6]
}

array[3] {
  [1]=> int[2]
  [3]=> int[4]
  [5]=> int[6]
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.

Niels

15 years ago

Here is a array_union[$a, $b]:

Shawn Pyle

13 years ago

array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

sapenov at gmail dot com

17 years ago

If you need to supply arbitrary number of arguments
to array_intersect[] or other array function,
use following function:

$full=call_user_func_array['array_intersect', $any_number_of_arrays_here];

blu at dotgeek dot org

17 years ago

Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,



and wants to know if the same person bought the same thing today and yesterday and use array_intersect[$orders_today, $orders_yesterday] you'll get as result:



but we can get around that by serializing the inner arrays:


so that array_map["unserialize", array_intersect[$orders_today, $orders_yesterday]] will return:



showing us who bought the same thing today and yesterday =]

[]s

yuval at visualdomains dot com

7 years ago

Using isset to achieve this, is many times faster:



Results:

Array
[
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
]
Took 4.7170009613037
[
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
]
Took 0.056024074554443

array_intersect: 4.717
array_flip+isset: 0.056

dml at nm dot ru

11 years ago

The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

matang dot dave at gmail dot com

7 years ago

Take care of value types while using array_intersect function as there is no option for strict type check as in in_array function.

$array1 = array[true,2];
$array2 = array[1, 2, 3, 4, 5, 6];

var_dump[array_intersect[$array1, $array2]];

result is :
array[2] {
        [0] =>  bool[true]
        [1]  =>  int[2]
}

info at iridsystem dot it

7 years ago

This function is able to sort an array based on another array that contains the order of occurrence. The values that are not present will be transferred into the end of the resultant.
Questa funzione permette di ordinare i valori di un array [$tosort] basandosi sui valori contenuti in un secondo array [$base], i valori non trovati verranno posizionati alla fine dell'ordinamento senza un'ordine specifico.

Esfandiar -- e.bandari at gmail dot com

14 years ago

Regarding array union:  Here is a faster version array_union[$a, $b]

But it is not needed!  See below.

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E

theking at king dot ma

4 months ago

I use array_intersect for a quick check of $_GET parameters;



the file will die with a 400 error if cust_id or prod_id or both are missing from $_GET. But i could be used on $_POST and $_REQUEST as  well obviously.

Anonymous

1 year ago

array_intersect             use Value, not callback
array_uintersect            use Value, callback receives Value
array_intersect_key         use Key, not callback
array_intersect_ukey        use Key, callback receives Key
array_intersect_assoc       use Both, not callback
array_intersect_uassoc      use Both, callback receives Key ONLY
array_uintersect_assoc      use Both, callback receives Value ONLY
array_uintersect_uassoc     use Both, One callback receives the Key, the other receives the Value.

Ehsan.Chavoshi.com

3 years ago

I wrote this function to recursively replace array keys with array values [flip] and fill values with defined value. it can be used for recursive array intersect functions .

Yohann

12 years ago

I used array_intersect in order to sort an array arbitrarly:

Chủ Đề