Sort an array in PHP
Sharmin Shanta

Sharmin Shanta @sharminshanta

About: Backend Engineer | 5+ yrs | PHP | Python | Microservices | MySQL | MongoDB | Redis | Elasticsearch | JavaScript

Location:
Dhaka, Bangladesh
Joined:
Oct 3, 2024

Sort an array in PHP

Publish Date: Dec 4 '24
1 0
$arr['one'] = 1;
$arr['three'] = 3;
$arr['four'] = 4;
$arr['two'] = 2;
$arr['five'] = 5;

sort($arr); // sort the value as ascending order and return the new array: [0 => 1, 1 => 2, ...]
rsort($arr); // sort the value as descending order and return the new array: [0 => 5, 1 => 4, ...]
asort($arr); // sort the value as ascending order and return the array with the actual key: ['one' => 1, 'two => 2, ...]
arsort($arr); // sort the value as descending order and return the array with the actual key: ['five' => 5, 'four => 4, ...]
ksort($arr); // sort the key as ascending order and return the array with the actual value: ['five' => 5, 'four => 4, 'one' => 1, ...]
krsort($arr); // sort the key as descending order and return the array with the actual value: ['two' => 2, 'three' => 3, 'one' => 1, ...]

print_r($arr);
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment