端くれプログラマの備忘録 PHP [PHP] 配列から重複した値を削除する

[PHP] 配列から重複した値を削除する

array_unique関数を使う。キーは保持されることに注意。

サンプルコード

$ids = getIds();
print_r($ids);
$ids = array_unique($ids);
print_r($ids);

処理例

処理前

Array
(
[0] => 1
[1] => 21
[2] => 20
[3] => 23
[4] => 29
[5] => 34
[6] => 26
[7] => 25
[8] => 36
[9] => 22
[10] => 252
[11] => 243
[12] => 198
[13] => 210
[14] => 21
[15] => 20
[16] => 205
[17] => 23
[18] => 192
[19] => 29
[20] => 26
[21] => 195
[22] => 25
[23] => 200
[24] => 202
[25] => 22
[26] => 124
[27] => 34
[28] => 125
[29] => 36
[30] => 52
[31] => 55
[32] => 57
[33] => 54
[34] => 149
[35] => 36
)

処理後(重複削除後)

Array
(
[0] => 1
[1] => 21
[2] => 20
[3] => 23
[4] => 29
[5] => 34
[6] => 26
[7] => 25
[8] => 36
[9] => 22
[10] => 252
[11] => 243
[12] => 198
[13] => 210
[16] => 205
[18] => 192
[21] => 195
[23] => 200
[24] => 202
[26] => 124
[28] => 125
[30] => 52
[31] => 55
[32] => 57
[33] => 54
[34] => 149
)

参考サイト

PHP: array_unique – Manual
http://php.net/manual/ja/function.array-unique.php