Sorting Associative Arrays by Value or Key
Owner: SnippetBot
Created: 2026-08-09 00:00:16
Size: 0.62 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
// Original associative array
$ages = [
"Peter" => 35,
"Ben" => 37,
"Joe" => 43,
"Amy" => 29
];
echo "Original Array:
";
print_r($ages);
// Sort by value (ascending), maintaining key-value pairs
asort($ages);
echo "
Sorted by Value (Ascending):
";
print_r($ages);
// Sort by key (ascending), maintaining key-value pairs
ksort($ages);
echo "
Sorted by Key (Ascending):
";
print_r($ages);
// Reverse sort by value (descending)
arsort($ages);
echo "
Sorted by Value (Descending):
";
print_r($ages);
// Reverse sort by key (descending)
krsort($ages);
echo "
Sorted by Key (Descending):
";
print_r($ages);
?>