Php sort
From w3cyberlearnings
Contents |
PHP function sort
This function sorts array by value without any user-defined function.
Syntax sort
- array: array input
- sorttype (optional):
- SORT_REGULAR - (default, don't change type and treat value as it is),
- SORT_NUMERIC - Treat value as numeric
- SORT_STRING - Treat value as string
- SORT_LOCAL_STRING - Treat value based on the local setting.
sort(array,sorttype);
Note
The sort function uses quicksort algorithm to sort.
Example 1
<?php $score = array(30,20,50,3,5,110,10); print_r($score); sort($score); print_r($score); ?>
Output
Array ( [0] => 30 [1] => 20 [2] => 50 [3] => 3 [4] => 5 [5] => 110 [6] => 10 ) Array ( [0] => 3 [1] => 5 [2] => 10 [3] => 20 [4] => 30 [5] => 50 [6] => 110 )
Example 2: sort by string
<?php $name = array(10,30,40,111,40); print_r($name); // print array sort($name,SORT_STRING); print_r($name); // print sort array ?>
Output
Array ( [0] => 10 [1] => 30 [2] => 40 [3] => 111 [4] => 40 ) Array ( [0] => 10 [1] => 111 [2] => 30 [3] => 40 [4] => 40 )
Example 3: sort numeric
Array ( [0] => 10 [1] => 30 [2] => 40 [3] => 111 [4] => 40 ) Array ( [0] => 10 [1] => 30 [2] => 40 [3] => 40 [4] => 111 )
Example 4: sort string
<?php $list = array('app1', 'app2', 'app0', 'app4', 'app40', 'app5'); print_r($list); sort($list, SORT_STRING); print_r($list); ?>
Output
Array ( [0] => app1 [1] => app2 [2] => app0 [3] => app4 [4] => app40 [5] => app5 ) Array ( [0] => app0 [1] => app1 [2] => app2 [3] => app4 [4] => app40 [5] => app5 )
Related Links
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys