[PHP] 配列の重複削除
PHPの配列から重複する値を削除する
配列をarray_unique()関数にかけると、配列内で中身が重複している値を統合してくれます。
配列比較
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$array = ["apple", 3, "hoge"=>"apple", "foo"=>"jump", 3]; | |
// 配列を型変換ありで重複削除 | |
var_dump(array_unique($array)); | |
// 配列を型変換なしで重複削除 | |
var_dump(array_unique($array, SORT_REGULAR)); | |
// --------------------- | |
$ php unique.php | |
array(3) { | |
[0]=> | |
string(5) "apple" | |
[1]=> | |
int(3) | |
["foo"]=> | |
string(4) "jump" | |
} | |
array(4) { | |
[0]=> | |
string(5) "apple" | |
[1]=> | |
int(3) | |
["foo"]=> | |
string(4) "jump" | |
[2]=> | |
string(1) "3" | |
} |
配列がネストしている配列を比較
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = [ | |
[1, 2, 3], | |
[1, 2, 3], | |
[3, 4, 5] | |
]; | |
var_dump(array_unique($arr, SORT_REGULAR)); | |
// ----------------------- | |
$ php unique2.php | |
array(3) { | |
[0]=> | |
array(3) { | |
[0]=> | |
int(1) | |
[1]=> | |
int(2) | |
[2]=> | |
int(3) | |
} | |
[1]=> | |
array(3) { | |
[0]=> | |
int(3) | |
[1]=> | |
int(4) | |
[2]=> | |
int(5) | |
} | |
} |
詳しい配列のオプションなどは本家のマニュアル参照
-
前の記事
ubuntuでセキュリティパッケージを自動インストール 2015.03.03
-
次の記事
PHP7と5の比較を早速試した 2015.04.03