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?

More than 3 years have passed since last update.

PHPで配列を比較して差分を抽出するときに使えるメソッド

Last updated at Posted at 2020-07-07

はじめに

PHPで配列の要素の比較をしたいと思い、調べていたら、「array_diff」というメソッドがあり、使ってみたら便利だったので、備忘録を残します。

使い方(例)

hoge.php
<?PHP
$array1 = ['a', 'b', 'c'];
$array2 = ['a', 'b', 'c'];
$array3 = ['b', 'c', 'a'];
$array4 = ['a', 'b'];
$array5 = ['a', 'b', 'c', 'd'];

// 順序、値が一致する場合
$diff1and2 = array_diff($array1, $array2);
print_r($diff1and2);
// Array()

// 順序が不一致、値が一致する場合
$diff1and3 = array_diff($array1, $array3);
print_r($diff1and3);
// Array()

// $array1と$array4の値が不一致($array1に「c」が存在)
$diff1and4 = array_diff($array1, $array4);
print_r($diff1and4);
// Array([2] => c)

// $array1と$array5の値が不一致($array5に「d」が存在)
$diff1and5 = array_diff($array1, $array5);
print_r($diff1and5);
// Array()

参考

array_diff

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?