PHP には配列をソートする関数が複数用意されています。 このページでは、それらの違いについて説明します。
主な相違点は次のとおりです。
$array['キー'] = '値';
| 関数名 | ソートの基準 | キーと値の相関関係 | ソート順 | 関連する関数 |
|---|---|---|---|---|
| array_multisort() | 値 | 文字列がキーの場合は維持し、数値添字配列の場合は維持しない | 最初の配列、あるいはソートオプション | array_walk() |
| asort() | 値 | 維持する | 昇順 | arsort() |
| arsort() | 値 | 維持する | 降順 | asort() |
| krsort() | キー | 維持する | 降順 | ksort() |
| ksort() | キー | 維持する | 昇順 | krsort() |
| natcasesort() | 値 | 維持する | 大文字小文字を区別しない自然順 | natsort() |
| natsort() | 値 | 維持する | 自然順 | natcasesort() |
| rsort() | 値 | 維持しない | 降順 | sort() |
| shuffle() | 値 | 維持しない | ランダム | array_rand() |
| sort() | 値 | 維持しない | 昇順 | rsort() |
| uasort() | 値 | 維持する | ユーザー定義 | uksort() |
| uksort() | キー | 維持する | ユーザー定義 | uasort() |
| usort() | 値 | 維持しない | ユーザー定義 | uasort() |
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.
The following code:
<?php
function usortTest($a, $b) {
var_dump($a);
var_dump($b);
return -1;
}
$test = array('val1');
usort($test, "usortTest");
$test2 = array('val2', 'val3');
usort($test2, "usortTest");
?>
Will output:
string(4) "val3"
string(4) "val2"
The first array doesn't get sent to the function.
Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.Another way to do a case case-insensitive sort by key would simply be:
<?php
uksort($array, 'strcasecmp');
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.