配列のソート

PHP には配列をソートする関数が複数用意されています。 このページでは、それらの違いについて説明します。

主な相違点は次のとおりです。

  • 配列のキーでソートするものと、値でソートするものがあります。 $array['キー'] = '値';
  • キーと値の相関関係をソート後にも保持するものと保持しないものがあります。 保持しないものは、ソート後にキーを (0,1,2 ... と) 振りなおします。
  • ソート順による違いがあります。アルファベット順、 昇順、降順、自然順、ランダム、ユーザー定義の順などです。
  • 注意: ソート関数は、すべて配列自身を直接変更します。 ソートした配列を新しく作って返すわけではありません。
  • これらのソート関数でふたつのメンバーが等しいと判断された場合、 それらの順番は保持されます。 PHP 8.0.0 より前のバージョンでは、 それらの並び順は未定義でした(並び順が場合によって変わる可能性がありました)。

ソート関数の特性
関数名 ソートの基準 キーと値の相関関係 ソート順 関連する関数
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()
+add a note

User Contributed Notes 2 notes

up
147
"Matthew Rice" Âś
13 years ago
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.
up
2
oculiz at gmail dot com Âś
15 years ago
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.