sort

(PHP 4, PHP 5, PHP 7, PHP 8)

sortSortiert ein Array in aufsteigender Reihenfolge

Beschreibung

function sort(array &$array, int $flags = SORT_REGULAR): bool

Sortiert array nach Werten in aufsteigender Reihenfolge.

Hinweis:

Wenn zwei Mitglieder als identisch verglichen werden, behalten sie ihre ursprüngliche Reihenfolge bei. Vor PHP 8.0.0 war die relative Sortierung im sortierten Array nicht definiert.

Hinweis:

Diese Funktion weist den Elementen des Arrays array neue Schlüssel zu. Bestehende Schlüssel, die bereits zugewiesen wurden, werden entfernt statt einfach nur die Schlüssel neu anzuordnen

Hinweis:

Setzt den internen Zeiger des Arrays auf das erste Element zurück.

Parameter-Liste

array

Das Eingabe-Array.

flags

Der optionale zweite Parameter flags kann mit folgenden Werten genutzt werden, um das Sortierverhalten zu ändern:

Flags für den Sortiertyp:

Rückgabewerte

Gibt immer true zurück.

Changelog

Version Beschreibung
8.2.0 Der Rückgabewert ist nun true vorher war es bool.

Beispiele

Beispiel #1 sort()-Beispiel

<?php

$fruits = array("Zitrone", "Orange", "Banane", "Apfel");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

fruits[0] = Apfel
fruits[1] = Banane
fruits[2] = Orange
fruits[3] = Zitrone

Die Früchte wurden in alphabetischer Reihenfolge sortiert.

Beispiel #2 sort()-Beispiel mit natürlicher Sortierung ohne Beachtung der Groß- und Kleinschreibung

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

Die Früchte wurden wie durch natcasesort() sortiert.

Anmerkungen

Hinweis:

Wie die meisten PHP-Sortierfunktionen benutzt sort() eine Implementierung von » Quicksort. Das Pivotelement wird aus der Mitte der Partition gewählt, was zu optimaler Laufzeit für bereits sortierte Arrays führt. Das ist jedoch ein Implementierungsdetail, auf das man sich nicht verlassen sollte.

Warnung

Vorsicht ist geboten wenn Arrays mit Werten unterschiedlichen Typs sortiert werden, weil sort() unerwartete Ergebnisse liefern kann, wenn flags SORT_REGULAR ist.

Siehe auch

add a note

User Contributed Notes 35 notes

up
230
phpdotnet at m4tt dot co dot uk
16 years ago
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
        )
 
)
*/

?>
up
13
Walter Tross
14 years ago
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
?>
up
3
aminkhoshzahmat at gmail dot com
6 years ago
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
)
up
1
Md. Abutaleb
6 years ago
<?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. 
?>
up
1
Abhishek Banerjee
10 years ago
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
        )

)
*/

?>
up
2
eriewave at hotmail dot com
16 years ago
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
up
3
danm68 at gmail dot com
17 years ago
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.
up
2
matpatnik at hotmail dot com
18 years ago
This function will sort entity letters eg:&eacute;

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;
}
up
2
ajanata at gmail dot com
14 years ago
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).
up
2
joris at mangrove dot nl
19 years ago
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.
up
1
williamprogphp at[pleaseNOTSPAM] yahoo d
12 years ago
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
up
1
peek at mailandnews dot com
25 years ago
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);'));
up
0
r at rcse dot de
7 years ago
Here is no word about sorting UTF-8 strings by any collation. This should not be so uncommon?
up
0
me[ at ]szczepan[ dot ]info
13 years ago
Sorting the keys, but keep the values in order is not possible by just ordering, because it would result in a new array. This is also the solution: Create a new array

<?php
$a = array(9=>"a",8=>"c",5=>"d");

$keys = array_keys($a);
sort($keys);
$result = array_combine($keys, array_values($a));

//Result : array(5=>"a",8=>"c",9=>"d");
?>
up
0
alex dot hristov dot 88 at gmail dot com
15 years ago
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key) 
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else    
                    arsort($temp);
            }
            else 
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc') 
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key) 
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else    
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
up
0
cmarshall at gmx dot de
15 years ago
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('ä' = 'ae', 'ö' = 'oe', 'ü' = 'ue', 'ß' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace(