Sorting Array in php

Using sort()

The following code showing the sort() function results in the array being sorted into ascending alphabetical order

$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);

The array elements will now appear in the order Oil, Spark Plugs, Tires

$prices = array(100, 10, 4);

The prices will now appear in the order 4, 10, 100

Using asort() and ksort() to sort arrays

If you are using an array with descriptive keys to store items and their prices, you need to use different kinds of sort functions to keep keys and values together as they are sorted

The following code creates an 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);

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, you want to sort by description, you can use ksort(), which sorts by key rather than value.

Leave a Comment