複数の配列の共通する要素を調べる
■ 複数の配列の共通する要素を調べる
array_intersec関数は、array_dif関数とは逆に、ある配列と別の配列に共通する要素を返します。 配列 = array_intersec (配列1, 配列2, [・・・・・・・]) 例えば、次のような場合には、配列「$a」も配列「$b」にもある「1」と「3」が返されます。 $a = array(1, 2, 3); $b = array(1, 3, 5); $c = array_intersec($a, $b); // $c[0] = 1 // $c[2] = 3 となる array_intersect_assoc関数は、要素の値だけでなくキーも確認します。 配列 = array_intersec_assoc (配列1, 配列2, [・・・・・・・]) 次の場合には、配列「$a」と「$b」に共に存在し、かつキーも同じである「1」だけが返されます。 $a = array(1, 2, 3); $b = array(1, 3, 5); $c = array_intersect_assoc($a, $b); // $c[0] = 1 となる <?php $a = array("foo", "boo", 1, 2, 3); $b = array("foo", "woo", 2, 4, 6); $c = array_intersect($a, $b); $d = array_intersect_assoc($a, $b); header("Content-Type: text/plain; charset=EUC-JP"); echo "[array_intersect]\n"; foreach ($c as $key => $value) { echo "\$c[{$key}] = {$value}\n"; } echo "\n"; echo "[array_intersect_assoc]\n"; foreach ($d as $key => $value) { echo "\$d[{$key}] = {$value}\n"; } ?> <戻る
array_intersec関数は、array_dif関数とは逆に、ある配列と別の配列に共通する要素を返します。
配列 = array_intersec (配列1, 配列2, [・・・・・・・])
例えば、次のような場合には、配列「$a」も配列「$b」にもある「1」と「3」が返されます。
$a = array(1, 2, 3); $b = array(1, 3, 5); $c = array_intersec($a, $b); // $c[0] = 1 // $c[2] = 3 となる
array_intersect_assoc関数は、要素の値だけでなくキーも確認します。
配列 = array_intersec_assoc (配列1, 配列2, [・・・・・・・])
次の場合には、配列「$a」と「$b」に共に存在し、かつキーも同じである「1」だけが返されます。
$a = array(1, 2, 3); $b = array(1, 3, 5); $c = array_intersect_assoc($a, $b); // $c[0] = 1 となる <?php $a = array("foo", "boo", 1, 2, 3); $b = array("foo", "woo", 2, 4, 6); $c = array_intersect($a, $b); $d = array_intersect_assoc($a, $b); header("Content-Type: text/plain; charset=EUC-JP"); echo "[array_intersect]\n"; foreach ($c as $key => $value) { echo "\$c[{$key}] = {$value}\n"; } echo "\n"; echo "[array_intersect_assoc]\n"; foreach ($d as $key => $value) { echo "\$d[{$key}] = {$value}\n"; } ?>
$a = array(1, 2, 3); $b = array(1, 3, 5); $c = array_intersect_assoc($a, $b); // $c[0] = 1 となる
<?php $a = array("foo", "boo", 1, 2, 3); $b = array("foo", "woo", 2, 4, 6); $c = array_intersect($a, $b); $d = array_intersect_assoc($a, $b); header("Content-Type: text/plain; charset=EUC-JP"); echo "[array_intersect]\n"; foreach ($c as $key => $value) { echo "\$c[{$key}] = {$value}\n"; } echo "\n"; echo "[array_intersect_assoc]\n"; foreach ($d as $key => $value) { echo "\$d[{$key}] = {$value}\n"; } ?>
<戻る