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 5 years have passed since last update.

複数の配列で2回以上出現する値を抽出する方法

Posted at

array_intersectではすべての配列の共通項を出せるが、いずれかの配列の共通項を出したいときに迷ったのでメモ。
もっと良い方法あったら教えてください。

array_intersect_any.php
<?php
$a = ['hoge', 'fuga'];
$b = ['hoge', 'fuga', 'piyo'];
$c = ['hoge', 'fuga', 'piyo', 'hogehoge'];

/**
 * すべての配列をマージして出現回数が2回以上の値だけを抽出する
 * 連想配列には対応していない
 * 一つの配列に同じ値が2つあっても共通項として抽出される
 * 
 * @access
 * @return array
 */
function array_intersect_any()
{
    $list = call_user_func_array('array_merge', array_filter(func_get_args(), 'is_array'));
    $count = array_count_values($list);

    return array_unique(array_filter($list, function ($l) use ($count) {
        return $count[$l] > 1;
    }));
}

var_dump(array_intersect_any($a, $b, $c));
/*
array(3) {
  [0]=>
  string(4) "hoge"
  [1]=>
  string(4) "fuga"
  [4]=>
  string(4) "piyo"
}
*/

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?