-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortAssociativeAndIndexArray.php
More file actions
88 lines (78 loc) · 2.08 KB
/
SortAssociativeAndIndexArray.php
File metadata and controls
88 lines (78 loc) · 2.08 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
//function to sort index array in ascending order
$num=array(2,4,3,8,9);
sort($num);//ascending order
$length=count($num);
for ($i=0;$i<$length;$i++){
echo $num[$i]."<br>";
}
echo "<br>";
//function to sort index array in descending order
rsort($num);
$len=count($num);
for ($i=0;$i<$len;$i++){
echo $num[$i]."<br>";
}
echo"<br><br>";
//sorting associative array in ascending order by value
echo "<br>age in ascending order by value is:<br>";
$age=array(
"ram"=>29,"hari"=>34,"sita"=>32
);
asort($age);
foreach($age as $key=>$value){
echo "name: ".$key." and age: ".$value."<br>";
}
echo "<br>age in descending order by value is:<br>";
//sorting associative array in descending order by value
arsort($age);
foreach ($age as $key=>$value){
echo "name: ".$key." and age: ".$value."<br>";
}
//arranging associative array in ascending order by key
echo "<br>sorting in ascending order by key is:<br>";
$favfruits=array(
"first"=>["mango","orange","apple"],
"second"=>["banana","grapes","strawberry"],
"third"=>["pineapple","cherry","litchi"]
);
ksort($favfruits);
foreach ($favfruits as $key => $fruits) {
echo"<strong>$key:</strong><br>";
foreach ($fruits as $fruit){
echo "-$fruit<br>";
}
}
echo "<br>sorting inner array alphabetically in ascending order<br>";
// Sort each inner array alphabetically
foreach ($favfruits as &$fruits) {
sort($fruits); // sort() arranges values in ascending order
}
unset($fruits); // break reference
// Display the sorted result
foreach ($favfruits as $key => $fruits) {
echo "<strong>$key:</strong><br>";
foreach ($fruits as $fruit) {
echo "- $fruit<br>";
}
}
echo "<br>sorting in descending order by key is:<br>";
krsort($favfruits);
foreach ($favfruits as $key => $fruits) {
echo "<strong>$key:</strong><br>";
foreach ($fruits as $fruit){
echo "-$fruit<br>";
}
}
echo "<br>sorting inner array alphabetically in descending order<br>";
foreach ($favfruits as $key => &$fruits) {
rsort($fruits);
}
unset($fruits);
foreach($favfruits as $key=>$fruits){
echo "<strong>$key:</strong><br>";
foreach($fruits as $fruit){
echo "-$fruit<br>";
}
}
?>