PHP Sorting Arrays
PHP Sorting Arrays
PHP - Sort
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending
Example:
• <?php
• $cars = array("Volvo", "BMW", "Toyota");
• sort($cars);
• ?>
Sort Array in Ascending Order - sort()
• The following example sorts the elements of the $numbers array in
ascending numerical order:
Example:
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Sort Array in Descending Order - rsort()
• The following example sorts the elements of the $cars array in
descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
Sort Array in Descending Order - rsort()
• The following example sorts the elements of the $numbers array in
descending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Sort Array (Ascending Order), According to
Value - asort()
• The following example sorts an associative array in ascending order, according to the
value:
Example
<?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>";
}
?>
Sort Array (Ascending Order), According to
Key - ksort()
• The following example sorts an associative array in ascending order,
according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Sort Array (Descending Order), According to
Value - arsort()
• The following example sorts an associative array in descending order,
according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Sort Array (Descending Order), According to
Key - krsort()
• The following example sorts an associative array in descending order,
according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
PHP Global Variables -
Superglobals
PHP Global Variables - Superglobals
• Several predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do
anything special.