1. toadstomochi

    Posted

    toadstomochi
Changes in title
+php 配列 重複した要素の削除 array_unique()
Changes in tags
Changes in body
Source | HTML | Preview

配列の重複要素を削除

array_unique()

qiita.php
$array = ["aaaa","wwww","eeee","aaaa","tttt","WWWW","eeee"];
$array = (array_unique($array));
//Array ( [0] => aaaa [1] => wwww [2] => eeee [4] => tttt [5] => WWWW )
連想配列の場合
qiita.php
$array = array(
    array('takuya', 'jun', 'yoshiko', 'miki'),
    array('kazuki', 'aya', 'yoshiko', 'miki'),
    array('takuya', 'jun', 'yoshiko', 'miki'),
);

$array = array_unique($array, SORT_REGULAR);
//Array ( [0] => Array ( [0] => takuya [1] => jun [2] => yoshiko [3] => miki ) [1] => Array ( [0] => kazuki [1] => aya [2] => yoshiko [3] => miki ) )

第2引数にSORT_REGULARを指定しました。

配列内に要素が何種類あるか調べる。

qiita.php
$array = ["aaaa","wwww","eeee","aaaa","tttt","WWWW","eeee"];
$count = count(array_unique($array));
//5
qiita.php
$array = array(
    array('takuya', 'jun', 'yoshiko', 'miki'),
    array('kazuki', 'aya', 'yoshiko', 'miki'),
    array('takuya', 'jun', 'yoshiko', 'miki'),
);

$count = count(array_unique($array, SORT_REGULAR));
//2

//要素が全て同じ
$array = array(
    array('takuya', 'jun', 'yoshiko', 'miki'),
    array('takuya', 'jun', 'yoshiko', 'miki'),
    array('takuya', 'jun', 'yoshiko', 'miki'),
);

$count = count(array_unique($array, SORT_REGULAR));
//1