Page 146 - Open Soource Technologies 304.indd
P. 146
Web Technologies-I
Notes We can sort values by numerical order too. If we have an array containing the prices of products,
we can sort it into ascending numeric order as shown:
$prices = array( 100, 10, 4 );
sort($prices);
The prices will now be in the order 4, 10, 100.
Must be understood that the sort function is case-sensitive. All capital letters
come before all lowercase letters. So “A” is less than “Z”, but “Z” is less
than “a”.
Using asort() and ksort() to Sort Associative Arrays
If we are using an associative array to store items and their prices, we need to use different
kinds of sort functions to keep keys and values together as they are sorted.
The following code creates an associative array containing the three products and their associated
prices, and then sorts the array into ascending price order.
$prices = array( ‘Tires’=>100, ‘Oil’=>10, ‘Spark Plugs’=>4 );
asort($prices);
The function asort() orders the array according to the value of each element. In the array, the
values are the prices and the keys are the textual descriptions. If instead of sorting by price we
want to sort by description, we use ksort(), which sorts by key rather than value. This code will
result in the keys of the array being ordered alphabetically—Oil, Spark Plugs, Tires.
$prices = array( ‘Tires’=>100, ‘Oil’=>10, ‘Spark Plugs’=>4 );
ksort($prices);
Sorting in Reverse
You have seen sort(), asort(), and ksort(). These three different sorting functions all sort an
array into ascending order. Each of these functions has a matching reverse sort function to sort
an array into descending order. The reverse versions are called rsort(), arsort(), and krsort().
The reverse sort functions are used in the same way as the sorting functions. The rsort() function
sorts a single dimensional numerically indexed array into descending order. The arsort() function
sorts a one-dimensional associative array into descending order using the value of each element.
The krsort() function sorts a one-dimensional associative array into descending order using the
key of each element.
6.5 Working with Array
Following example is defining working of array:
Example:
<pre>
<?
$Thearray= array (“Zero”,”one”,”two”,”three”,”four”,”five”,”six”,”seven”,”eight”,”nine”)
?>
Thearray[0]: <? print $Thearray[0]; ?>
Thearray[1]: <? print $Thearray[1]; ?>
140 LOVELY PROFESSIONAL UNIVERSITY