配列のソート

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 add a note

User Contributed Notes 3 notes

up
129
"Matthew Rice"
10 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
24
oculiz at gmail dot com
13 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.
up
-26
Hayley Watson
7 years ago
Stabilizing the sort functions (in this case, usort).

<?php
function stable_usort(&$array, $cmp)
{
   
$i = 0;
   
$array = array_map(function($elt)use(&$i)
    {
        return [
$i++, $elt];
    },
$array);
   
usort($array, function($a, $b)use($cmp)
    {
        return
$cmp($a[1], $b[1]) ?: ($a[0] - $b[0]);
    });
   
$array = array_column($array, 1);
}
?>

Tags each array element with its original position in the array so that when the comparison function returns 0 the tie can be broken to put the earlier element first.
To Top