Quantcast
Channel: Excel Management Web Wonders
Viewing all articles
Browse latest Browse all 11

Sorting Arrays in PHP

$
0
0

You can put as many elements as you want in an array. These elements can be sorted in alphabetical, numerical, descending or ascending order.

We will learn a few different types of ways that arrays can be sorted.

Here are two example that sort any arrays:
sort() – ascending order
rsort() – descending order

Below are two examples of sorting arrays in ascending order; sort(). The first is alphabetical because it’s words and the second is numerical because it’s numbers.

<?php
$cars = array(“Volvo”, “BMW”, “Toyota”);
sort($cars);$clength = count($cars);
for($x = 0; $x <  $clength; $x++) {
echo $cars[$x];
echo “<br>”;
}
?>

The output for this would be:
BMW
Toyota
Volvo

<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x <  $arrlength; $x++) {
echo $numbers[$x];
echo “<br>”;
}
?>

The output for this would be:
2
4
6
11
22

If you would like to sort an array backwards alphabetically or numerically, you use rsort().
You’ll see the two examples below are written in the same way as our previous examples except with rsort().

<?php
$cars = array(“Volvo”, “BMW”, “Toyota”);
sort($cars);$clength = count($cars);
for($x = 0; $x <  $clength; $x++) {
echo $cars[$x];
echo “<br>”;
}
?>

The output for this would be:
Volvo
Toyota
BMW

<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x <  $arrlength; $x++) {
echo $numbers[$x];
echo “<br>”;
}
?>

The output for this would be::
22
11
6
4
2


Viewing all articles
Browse latest Browse all 11

Trending Articles