Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect -- Вычислить схождение массивов

Описание

array array_intersect ( array array1, array array2 [, array ...] )

Функция array_intersect() возвращает массив, содержащий значения массива array1, которые содержат все перечисленные в аргументах массивы. Обратите внимание, что ключи сохраняются.

Пример 1. Пример использования array_intersect()

$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);

В результате выполнения переменная $result будет содержать
Array
(
    [a] => green
    [0] => red
)

Замечание: Два элемента считаются одинаковыми тогда и только тогда, когда (string) $elem1 === (string) $elem2. Другими словами, когда их строковые представления идентичны.

См.также array_diff().



array_key_exists> <array_intersect_ukey
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
array_intersect
aaron
17-Dec-2006 09:36
this one will work with associative arrays.  also an overwrite function to only replace those elements in the first array.

<?php

function array_union()
{
    if (
func_num_args() < 2) { return; }
   
$arrays = func_get_args();
   
$outputArray = array_shift($arrays);
   
$remaining = count($arrays);
    for (
$i=0; $i<$remaining; $i++)
    {
       
$nextArray = $arrays[$i];
        foreach (
$nextArray as $key=>$value)
        {
           
$outputArray[$key] = $value;
        }
    }
    return
$outputArray;
}

function
array_overwrite()
{
    if (
func_num_args() < 2) { return; }
   
$arrays = func_get_args();
   
$outputArray = array_shift($arrays);
   
$remaining = count($arrays);
    for (
$i=0; $i<$remaining; $i++)
    {
       
$nextArray = $arrays[$i];
        foreach (
$nextArray as $key=>$value)
        {
            if (
array_key_exists($key, $outputArray)) {    $outputArray[$key] = $value; }
        }
    }
    return
$outputArray;
}

?>
Niels
19-Sep-2006 04:53
Here is a array_union($a, $b):

<?php
                                       
//  $a = 1 2 3 4
   
$union =                            //  $b =   2   4 5 6
       
array_merge(
           
array_intersect($a, $b),    //         2   4
           
array_diff($a, $b),         //       1   3
           
array_diff($b, $a)          //               5 6
       
);                              //  $u = 1 2 3 4 5 6
?>
nthitz at gmail dot com
08-Jun-2006 09:09
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
terry(-at-)shuttleworths(-dot-)net
07-Feb-2006 07:42
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
tom p
04-Nov-2005 06:54
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
sapenov at gmail dot com
10-Jun-2005 01:11
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);
SETS INTERSECTION
18-May-2005 11:19
$a = array(1,2,3,4,5,2,6,1);  /* repeated elements --> $a is not a set */
$b = array(0,2,4,6,8,5,7,9,2,1);  /* repeated elements --> $b is not a set */

$ua = array_merge(array_unique($a));  /* now, $a is a set */
$ub = array_merge(array_unique($b));  /* now, $b is a set */

$intersect = array_merge(array_intersect($ua,$ub));

Note: 'array_merge' removes blank spaces in the arrays.
Note: order doesn't matter.

In one line:

$intersect_a_b = array_merge(array_intersect(array_merge(array_unique($a)), array_merge(array_unique($b))));

Additions/corrections wellcome...

gRiNgO
drew at iws dot co dot nz
21-Apr-2005 08:04
Just a handy tip.

If you want to produce an array from two seperate arrays on their intersects, here you go:

<?

$a = array("branches","E_SHOP");
$b = array("E_SHOP","Webdirector_1_0");

print join("/",array_merge(array_diff($a, $b), array_intersect($a, $b), array_diff($b, $a)));

?>

Gives you:

/branches/E_SHOP/Webdirectory_1_0
blu at dotgeek dot org
14-Oct-2004 05:34
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today
[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571