To sort an array value there is function available in PHP.But i’ll show you the same things without using of in-built PHP function.
First see array sorting in ascending order without in-built function:
<?php
$a=array(5,15,25,7);
for($j = 0; $j < count($a); $j ++) {
for($i = 0; $i < count($a)-1; $i ++){
if($a[$i] > $a[$i+1]) {
$temp = $a[$i+1];
$a[$i+1]=$a[$i];
$a[$i]=$temp;
}
}
}
echo "Sorted Array is: ";
echo "<br />";
print_r($a);
// Output
Sorted Array is:
array(5,7,15,25);
Now see the in-built function:
- sort() – sort arrays in ascending order
- rsort() – sort arrays in descending order
- asort() – sort associative arrays in ascending order, according to the value
- ksort() – sort associative arrays in ascending order, according to the key
- arsort() – sort associative arrays in descending order, according to the value
- krsort() – sort associative arrays in descending order, according to the key
1. sort() – This function is used for sorting array in ascending order.
<?php
$lang = array("PHP", "Java", "AJAX");
print_r(sort($lang));
// Output
array("AJAX", "Java", "PHP");
2. rsort() – sort arrays in descending order.
<?php
$lang = array("PHP", "AJAX", "Java");
print_r(rsort($lang));
// Output array("PHP", "Java", "AJAX");
3. asort() – sort associative arrays in ascending order, according to the value.
<?php
$age = array("Doe"=>"30", "Ben"=>"27", "Joe"=>"13");
$new_arr = asort($age);
foreach($new_arr as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
// Output
Key=Joe, Value=13
Key=Ben, Value=27
Key=Doe, Value=30
4. ksort() – sort associative arrays in ascending order, according to the key.
<?php
$age = array("Doe"=>"30", "Ben"=>"27", "Joe"=>"13");
$new_arr = ksort($age);
foreach($new_arr as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
// Output
Key=Ben, Value=27
Key=Doe, Value=30
Key=Joe, Value=13
5. arsort() – sort associative arrays in descending order, according to the value.
<?php
$age = array("Doe"=>"30", "Ben"=>"27", "Joe"=>"13");
$new_arr = arsort($age);
foreach($new_arr as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
// Output
Key=Doe, Value=30
Key=Ben, Value=27
Key=Joe, Value=13
6. krsort() – sort associative arrays in descending order, according to the key.
<?php
$age = array("Doe"=>"30", "Ben"=>"27", "Joe"=>"13");
$new_arr = krsort($age);
foreach($new_arr as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
// Output
Key=Joe, Value=13
Key=Doe, Value=30
Key=Ben, Value=27