Table of Contents
Sort Functions For Arrays In this chapter, we will go through the following PHP array sort functions:
The following example sorts the elements of the $cars array in ascending alphabetical order:
<h4>Sort_Array_in_Ascending_Order</h4>
<p>The following example sorts the elements of the $cars array in ascending alphabetical order:</p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
<hr>
<p>The following example sorts the elements of the $numbers array in ascending numerical order:</p>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Result View Example
The following example sorts the elements of the $cars array in descending alphabetical order:
<h4>Sort_Array_in_Descending_Order</h4>
<p></p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
<hr>
<p>The following example sorts the elements of the $numbers array in descending numerical order:</p>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Result View Example
The following example sorts an associative array in ascending order, according to the value:
<h4>According_to_Value_Ascending</h4>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result View Example
The following example sorts an associative array in ascending order, according to the key:
<h4>According_to_Key_Ascending</h4>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result View Example
The following example sorts an associative array in descending order, according to the value:
<h4>According_to_Value_Descending</h4>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result View Example
The following example sorts an associative array in descending order, according to the key:
<h4>According_to_Key_Descending</h4>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result View Example
Document in project
You can Download PDF file.