Fri, 17 May 2024


Sorting Arrays PHP

By: Nathalie, NetArt Media
Wed, 1 August 2018
Sorting Arrays PHP

As I've mentioned in the past, it's always good to have a number of tools in your PHP box that can come to the rescue in any given situation. Those who regularly develop scripts and websites with PHP are well aware of how things can pop up that may need another method of processing and returning. Array sort can be one of those tools.

There are several variations of array sort that can be used, but today I will cover 'ksort', which allows for sorting array keys in an ascending manner according to their alphabetical or numerical value and 'asort', which does the same, only for array values.


The array of guitars within the code block contain prices for each brand. 'ksort' creates an ascending order of the keys of the array. Below is the result in a browser.

Les Paul: $1600
Stratocaster: $1000
Telecaster: $900

As we would expect, the array keys are returned in an ascending list. Notice my use of an HTML code for the dollar sign. This is used to avoid any mishaps, as the dollar sign defines a variable in PHP. Of course, you could always simply escape an actual dollar sign, but I choose to do it this way.


As discussed above, 'asort' puts the values of the array into an ascending order. The result of this code block is...

Telecaster: $900
Stratocaster: $1000
Les Paul: $1600

Now we can create a while statement that only returns the guitars that are equal to or less than $1000.


Telecaster: $900
Stratocaster: $1000

As the while statement defines, only the 2 guitars that are either equal to or less than $1000 are returned. Now, of course you could expand on the conditions, perhaps using an if statement which compares a variable that has been passed from an HTML form or a search engine. There aren't many limits to what you can do with array sort.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox