0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

2つの配列から共通する値と共通しない値を作成する方法

Last updated at Posted at 2025-07-13
$a = [1,2,3,4,19];
$b = [1, 4];

上記の2つのインデックス配列があります。
PHPで値が被る配列と被らない配列を作成して、新たな変数を作成したいという要望がありました。

PHPで2つの配列間の共通する値(被る値)と共通しない値(被らない値)を作成するには、以下のように array_intersect()array_diff() 関数を使用できます。

<?php
$a = [1, 2, 3, 4, 19];
$b = [1, 4];

// 被る値(共通する値)
$intersect = array_intersect($a, $b);

// 被らない値(共通しない値)
$diff = array_diff($a, $b);

echo "被る値(共通する値): ";
print_r($intersect);

echo "被らない値(共通しない値): ";
print_r($diff);
?>

このコードでは、まず array_intersect() を使って2つの配列の共通する要素を取得し、次にarray_diff()を使って $a 配列の中で$b配列に存在しない要素を取得します。

実行結果は以下のようになります。

被る値(共通する値): Array
(
    [0] => 1
    [3] => 4
)
被らない値(共通しない値): Array
(
    [1] => 2
    [2] => 3
    [4] => 19
)

このようにして、共通する値と共通しない値を持つ新しい変数を作成することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?