sort
(PHP 4, PHP 5, PHP 7, PHP 8)
sort — 配列を昇順にソートする
説明
array
を値で昇順にソートします。
注意:
比較結果が等しくなる二つの要素があった場合、それらの並び順は保持されます。PHP 8.0.0 より前のバージョンでは、ソートした配列におけるそれらの並び順は不定でした。
注意: この関数は、
array
パラメータの要素に対して新しいキーを割り当てます。 その際、単純にキーを並べ替える代わりに、 すでに割り当てられている既存のキーを削除してしまいます。
注意:
この関数をコールすると、配列の内部ポインタは最初の要素にリセットされます。
パラメータ
array
-
入力の配列。
flags
-
オプションの第二引数
flags
によりソートの動作を修正可能です。 使える値は下記の通りです:ソートタイプのフラグ:
-
SORT_REGULAR
- 通常通りに項目を比較します。 詳細は 比較演算子 で説明されています。 -
SORT_NUMERIC
- 数値として項目を比較します。 -
SORT_STRING
- 文字列として項目を比較します。 -
SORT_LOCALE_STRING
- 現在のロケールに基づいて、文字列として項目を比較します。 比較に使うロケールは、setlocale() 関数で変更できます。 -
SORT_NATURAL
- 要素の比較を文字列として行い、 natsort() と同様の「自然順」で比較します。 -
SORT_FLAG_CASE
-SORT_STRING
やSORT_NATURAL
と (ビットORで) 組み合わせて使い、 文字列のソートで大文字小文字を区別しないようにします。
-
戻り値
常に true
を返します。
例
例1 sort() の例
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>
上の例の出力は以下となります。
fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
fruits はアルファベットの昇順にソートされました。
例2 sort() で、大文字小文字を区別せずに自然順での並べ替えを行う例
<?php
$fruits = array(
"Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>
上の例の出力は以下となります。
fruits[0] = Orange1 fruits[1] = orange2 fruits[2] = Orange3 fruits[3] = orange20
fruits が natcasesort() と同じようにソートされました。
注意
注意: PHP の大半のソート関数と同様、sort() は » Quicksort でそれを実装しています。 ピボットは、既にソート済みの部分に対して時間的に最適なところを選択します。 しかしこれはあくまでも内部の実装の話なので、これに依存したコードを書いてはいけません。
flags
が
SORT_REGULAR
の場合に
複数の型が混在する配列をソートする場合には、注意してください。
sort() が期待しない結果を出力することがあります。
参考
- rsort() - 配列を降順にソートする
- 配列ソート関数の比較
User Contributed Notes 35 notes
Simple function to sort an array by a specific key. Maintains index association.
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
/*
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
*/
?>
<?php
/*
As I found the sort() function normally works as ascending order based on the following priority :
1. NULL
2. Empty
3. Boolean FALSE
4. String
5. Float
6. Int
7. Array
8. Object
Consider the following array:
*/
$a = ['fruit'=> 'apple', 'A' => 10, 20, 5, 2.5, 5=>'A new value', 'last' => 'value', TRUE, NULL, "", FALSE, array(), new StdClass];
sort($a);
var_dump($a);
#The output is:
array(13) {
[0]=>NULL
[1]=> string(0) ""
[2]=>bool(false)
[3]=>string(11) "A new value"
[4]=>string(5) "apple"
[5]=>string(5) "value"
[6]=> float(2.5)
[7]=> int(5)
[8]=>int(10)
[9]=>int(20)
[10]=>array(0) { }
[11]=> bool(true)
[12]=>object(stdClass)#1 (0) {}
}
//Hope it will remove your confusion when you're sorting an array with mix type data.
?>
Let's say we have a list of names, and it is not sorted.
<?php
$names = array('Amin', 'amir', 'sarah', 'Somayeh', 'armita', 'Armin');
sort($names); // simple alphabetical sort
print_r($names);
?>
Result is :
Array
(
[0] => Amin
[1] => Armin
[2] => Somayeh // actually it's not sort alphabetically from here!
[3] => amir // comparison is based on ASCII values.
[4] => armita
[5] => sarah
)
If you want to sort alphabeticaly no matter it is upper or lower case:
<?php
sort($names, SORT_STRING | SORT_FLAG_CASE);
print_r($names);
?>
Result is:
Array
(
[0] => Amin
[1] => amir
[2] => Armin
[3] => armita
[4] => sarah
[5] => Somayeh
)
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
echo "{$a[0]} {$a[1]} {$a[2]}";
sort($a);
echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
EDIT: To the original note by "phpdotnet at m4tt dot co dot uk"
Use array_push instead of $new_array[$k] for some reason it was
giving me string indexes.
Simple function to sort an array by a specific key. Maintains index association.
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
array_push($new_array, $array[$k]);
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
/*
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
Array
(
[12345] => Array
(
[id] => 12345
[first_name] => Joe
[surname] => Bloggs
[age] => 23
[sex] => m
)
[12347] => Array
(
[id] => 12347
[first_name] => Amy
[surname] => Jones
[age] => 21
[sex] => f
)
[12346] => Array
(
[id] => 12346
[first_name] => Adam
[surname] => Smith
[age] => 18
[sex] => m
)
)
*/
?>
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:
<?php
sort($array, ksort($array))
?>
-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.
-Dirk
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :
Sorting an array of objects will not always yield the results you desire.
As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!
By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.
Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
In order to make some multidimensional quick sort implementation, take advantage of this stuff
<?php
function quickSortMultiDimensional($array, $chave) {
if( count( $array ) < 2 ) {
return $array;
}
$left = $right = array( );
reset( $array );
$pivot_key = key( $array );
$pivot = array_shift( $array );
foreach( $array as $k => $v ) {
if( $v[$chave] < $pivot[$chave] )
$left[$k][$chave] = $v[$chave];
else
$right[$k][$chave] = $v[$chave];
}
return array_merge(
quickSortMultiDimensional($left, $chave),
array($pivot_key => $pivot),
quickSortMultiDimensional($right, $chave)
);
}
?>
I make it using the idea from pageconfig dot com
tks for viewing
This function will sort entity letters eg:é
I hope that help someone
function sort_entity($array) {
$total = count($array);
for ($i=0;$i<$total;$i++) {
if ($array[$i]{0} == '&') {
$array[$i] = $array[$i]{1}.$array[$i];
} else {
$array[$i] = $array[$i]{0}.$array[$i];
}
}
sort($array);
for ($i=0;$i<$total;$i++) {
$array[$i] = substr($array[$i],1);
}
return $array;
}
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:
usort($listing, 'strcasecmp');
This didn't work (why not?), but you can do a proper case insensitive sort like this:
usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));