ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Server Side Web Tutorial #6 - PHP Sorting Arrays

Updated on May 6, 2014

Recap of the Last Tutorial & Goals for This One

In our last tutorial, A Server Side Web Tutorial #5 - Working with PHP Indexed, Associative, and Multidimensional Arrays we defined the three types of arrays PHP supports. We then demonstrated the use of looping construct to list the array contents.

In this tutorial we will be mainly concerned with sorting arrays. An array can be sorted in alphabetical or numerical order, descending or ascending.

The PHP sort() Function

  • There are a number of flags which can be used with sort()::
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort(), see the example in the snapshots which follow. Basically, in will sort in an order that would be used by a human.
  • SORT_NUMERIC - compare items numerically
  • SORT_REGULAR - compare items normally
  • SORT_STRING - compare items as strings

An important thing to recognize about sort(). It is a boolean function which will return true of false based on the sort being successful or not.

Performing a Simple Sort With sort()

A very simple sort. No addition flags are set. The order in which the items are arranged is a normal acending alphabetical sort.
A very simple sort. No addition flags are set. The order in which the items are arranged is a normal acending alphabetical sort.

A Natural Order Sort Using natsort()

Notice the difference between an alphabetic sor ascending and a natural sort.  Huans would think this way 1 is before two and 10 is after 2. Computers "think" differently 1 is followed by 10 and then 2, etc.
Notice the difference between an alphabetic sor ascending and a natural sort. Huans would think this way 1 is before two and 10 is after 2. Computers "think" differently 1 is followed by 10 and then 2, etc.

A Numeric Sort

A simple numeric sort (ascending), negative numbers precede positive values.
A simple numeric sort (ascending), negative numbers precede positive values.

The PHP rsort() "Reverse" Sort Function

The rsort() function sorts strings or numeric values in reverse order. "rsort()" like sort() is a boolean function returning true or false based on whether the sort was successful or not. rsort(0 used the same flas as sort().

rsort() vs. natsort() For String Values

The rsort() without  the SORT_NATURAL fag be set does not match the intuitive way that humans would want the data sorted.
The rsort() without the SORT_NATURAL fag be set does not match the intuitive way that humans would want the data sorted.

Sorting An Associative Array Using asort() and arsort()

asort() is used to sort an associative array in ascending values.while arsort() is used to sort the array in descending values. The functions are boolean returning true or false based on the success or failure of the sort. The sort preserves the association between key and value pair.

Examples of Associative Function asort() and arsort() Use

An example of the sort of an associative array with asort(0. Note, the key/value relationship is preserved. The sort is in terms of ascending values.
An example of the sort of an associative array with asort(0. Note, the key/value relationship is preserved. The sort is in terms of ascending values.
A simple example or an arsort(). Just think "r" for reverse order.
A simple example or an arsort(). Just think "r" for reverse order.

Sorting According to Key Values: ksort() and krsort()

Instead of sorting by the value in a key/value array. One can sort based on the key value with the PHP ksort() function.in ascending order or krsort() to sort in descending order. The same set of flags used by sort(0 can be used by these functions. Again, as with all the other functions we have seen up to now, ksort() and krsort(0 return a boolean value of true or false.

Examples of the Use of ksort() and krsort()

ksort() is used to sort an associative array in ascending key value.
ksort() is used to sort an associative array in ascending key value.
krsort(0 is used to sort an associative array in descending value.
krsort(0 is used to sort an associative array in descending value.

The array_unique() Function

At times it may be desirable to remove duplicate values from an array. The PHP function array_unigue() does this.

Example of the Use of array_unique()

array_unique(0 returns a new array with duplicate values removed.
array_unique(0 returns a new array with duplicate values removed.

Finding Differences Between Arrays

The array_diff() function compares two arrays. The result is the differences in values ONLY.

The array_diff_key() function compares not only the value but also the key. If the values are the same and the keys are different, the function will in this in reporting the differences.

In this example, the first array has four elements while the third array has three. The fourth key/value pair is reported as a diff.
In this example, the first array has four elements while the third array has three. The fourth key/value pair is reported as a diff.
In this example, the arrays are similar to the previous screen shot. However in addition to the diff on the fourth term two keys b and c have different values. They are report as being diffs.
In this example, the arrays are similar to the previous screen shot. However in addition to the diff on the fourth term two keys b and c have different values. They are report as being diffs.

The array_sum() Function

The array_sum(0 function counts the occurrences of the values in the array.

An Example of the Use of array_count_value()

The array_count_values() can be a very useful function to have when knowing the frequency of some object occurring is needed
The array_count_values() can be a very useful function to have when knowing the frequency of some object occurring is needed

Wrap Up and What's Next

In this tutorial we started looking at different ways of sort an array. The functions occur in pairs to indicated ordering ascending or descending keys or values. The functions are:

  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order by value
  • ksort() - sort associative arrays in ascending order by key
  • arsort() - sort associative arrays in descending order,by value
  • krsort() - sort associative arrays in descending by key

We then covered a "sampling" of several useful built-in functions for working with arrays, We will see many more!

As far as the next tutorial we will turn our attention to how PHP interacts with HTML forms.


Please Rate This Tutorial as to its Usefulness

Cast your vote for Did this tutorial present information useful to you?
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)