# How sort an array in PHP

View: 728    Dowload: 0   Comment: 0   Post by: hanhga   Category: Forum PHPBB, VBB   Fields: Other

Sorting Numerically Indexed Arrays :

At first we will consider an array which contains string values. The code below sorts array elements in ascending alphabetical order:

\$flowers = array("rose", "daisy" , "orchid", "tulip", "camomile");
sort(\$flowers);

for (\$i=0; \$i <= 4; \$i++) //prints the array elements
echo \$flowers[\$i]."
";

?>

Now array elements will go in the alphabetical order. Output will be the following:

camomile
daisy
orchid
rose
tulip

We can sort values by numerical order too. If we have an array containing the prices

of  flowers, we can sort it into ascending numeric order. Have a look at the example:

\$prices = array(1.25, 0.75 , 1.15, 1.00, 0.50);
sort(\$prices);

for (\$i=0; \$i <= 4; \$i++) //prints the array elements
echo \$prices[\$i]."
";

?>

The prices will now be in the following order:

0.50
0.75
1.00
1.15
1.25

Note that the sort function is case sensitive, i.e. all capital letters come before

all lowercase letters. So "A" is less than "Z", but "Z" is less than "a".

Sorting Associative Arrays

If we are using an associative array we cannot sort an array by using the sort()

function. If we apply the sort() function on an associative array, it is sorted by

the numeric value of the index. To sort an associative array we need to use the

asort() function to keep keys and values together as they are sorted.

The following code creates an associative array containing the three

flowers and their associated prices, and then sorts the array into ascending price order:

foreach(\$shop as \$key => \$value)
echo \$key." costs ".\$value." dollars
";
//print the array elements
?>

The above example will output:

orchid costs 2.00 dollars
daisy costs 4.00 dollars
rose costs 5.00 dollars

The asort() function orders the array according to the value of each element.

In the array, the values are the prices and the keys are the names of the flowers.

If instead of sorting by price we want to sort by flower name, we use ksort()

function to sort an associative array according to the key.

The following code will result in the keys of the array being ordered alphabetically:

\$shop = array ( "rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00",
);
ksort(\$shop);

foreach(\$shop as \$key => \$value)
echo \$key." costs ".\$value." dollars
";
//print the array elements
?>

Output will be the following:

daisy costs 4.00 dollars
orchid costs 2.00 dollars
rose costs 5.00 dollars

Sorting Arrays in the Reverse Order :

We discussed sort(), asort(), and  ksort() functions. All these functions sort array

in the ascending order. Each of them has corresponding function that sorts an array

in the descending order. These reverse functions are called rsort(), arsort() and krsort() respectively.

Reverse sorting functions are used the same way as usual sorting functions.

Rsort() function sorts one-dimensional numerically indexed array by the values in reverse order.

Arsort() function sorts one-dimensional associative array by the values in reverse order.

Krsort() function sorts one-dimensional associative array by the keys in reverse order

At first we will consider an array which contains string values. The code below sorts array elements in ascending alphabetical order:

Posted on 15-12-2015

#### Comment:

To comment you must be logged in members.

## Files with category

• ### Document Management System in VB.Net

Category: Forum PHPBB, VBB     Fields: none

This is a Client Server project entitled Document Management System written in Vb.net and SQL Server Management Studio R2 2008 database for Mines and Geosciences Bureau . There are three (3) sections in the Mines and Geosciences Bureau, namely: under...

• ### Input Validation Using Filter Functions with php

Category: Forum PHPBB, VBB     Fields: Other

Filter functions in PHP might not be sexy, but they can improve the stability, security, and even maintainability of your code if you learn how to use them correctly.

• ### The Open/Closed Principle in PHP

Category: Forum PHPBB, VBB     Fields: Other

As usual, a good way to grasp what’s actually behind the curtain of the principle and how to take advantage of its benefits is by example. In this article I’ll be setting up a few approachable ones in an attempt to unveil the principle’s driving...

• ### Dependency Injection with Pimple in PHP

Category: Forum PHPBB, VBB     Fields: Other

In application development, we try to create independent modules so that we can reuse code in future projects. But, it’s difficult to create completely independent modules which provide useful functionality; their dependencies can cause maintenance...

• ### Working with Directories in PHP

Category: Forum PHPBB, VBB     Fields: Other

Let's start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a...

• ### Guide to Email (Text / HTML / Attachments) in PHP

Category: Forum PHPBB, VBB     Fields: Other

At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters.

• ### Dynamic Image Generation in PHP

Category: Forum PHPBB, VBB     Fields: Other

At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

• ### Form Processing with PHP

Category: Forum PHPBB, VBB     Fields: Other

Before you can process the information, you need to create an HTML form that will send information to your PHP script. There are two methods for sending data: POST and GET. These two types of sending information are defined in your HTML form...

File suggestion for you
• HTML-CSS template - 521 view People love naming things. And developers love acronyms. And thus here we are, finding ourselves with all of these CSS naming conventions and...

• Javascript - 354 view This puzzle has been asked. In this java puzzle, you have a series of numbers start (e.g. 1….N) and exactly one number in this series is missing. You...

• CorelDRAW Graphics - 817 view Combine (Ctrl + L): link object, the intersection of the objects will be created by the empty area.

• Codeigniter - 799 view I want that the typeahead list will show a list of names, and when I select one of the name to write the id value to a hidden field.

• HTML-CSS template - 1264 view capable of bending or being bent, able to be easily modified to respond to altered circumstances or conditions.

File suggestion for you
• HTML-CSS template - 521 view People love naming things. And developers love acronyms. And thus here we are, finding ourselves with all of these CSS naming conventions and...

• Javascript - 354 view This puzzle has been asked. In this java puzzle, you have a series of numbers start (e.g. 1….N) and exactly one number in this series is missing. You...

• CorelDRAW Graphics - 817 view Combine (Ctrl + L): link object, the intersection of the objects will be created by the empty area.

• Codeigniter - 799 view I want that the typeahead list will show a list of names, and when I select one of the name to write the id value to a hidden field.

• HTML-CSS template - 1264 view capable of bending or being bent, able to be easily modified to respond to altered circumstances or conditions.

File suggestion for you
• HTML-CSS template - 521 view People love naming things. And developers love acronyms. And thus here we are, finding ourselves with all of these CSS naming conventions and...

• Javascript - 354 view This puzzle has been asked. In this java puzzle, you have a series of numbers start (e.g. 1….N) and exactly one number in this series is missing. You...

• CorelDRAW Graphics - 817 view Combine (Ctrl + L): link object, the intersection of the objects will be created by the empty area.

• Codeigniter - 799 view I want that the typeahead list will show a list of names, and when I select one of the name to write the id value to a hidden field.

• HTML-CSS template - 1264 view capable of bending or being bent, able to be easily modified to respond to altered circumstances or conditions.

File suggestion for you
• HTML-CSS template - 521 view People love naming things. And developers love acronyms. And thus here we are, finding ourselves with all of these CSS naming conventions and...

• Javascript - 354 view This puzzle has been asked. In this java puzzle, you have a series of numbers start (e.g. 1….N) and exactly one number in this series is missing. You...

• CorelDRAW Graphics - 817 view Combine (Ctrl + L): link object, the intersection of the objects will be created by the empty area.

• Codeigniter - 799 view I want that the typeahead list will show a list of names, and when I select one of the name to write the id value to a hidden field.

• HTML-CSS template - 1264 view capable of bending or being bent, able to be easily modified to respond to altered circumstances or conditions.

Mega tags
Mega tags
Mega tags
Mega tags
• Javascript - 238 view Bing Search API is a set of REST interfaces that find web pages, news,...

• HTML-CSS template - 408 view Pinkrio is a strong and powerful XHTML/CSS template with a clean and...

• PostgreSQL - 1320 view In this article, I want to show some operations in both PostgreSQL &...

• Java mobile - 763 view If you missed the premiere of one of our virtual tech summits you'll...

• Mobile applications - 214 view In this tutorial we will try to create a Simple Image Viewer using...

• Embedded Systems - 1456 view Termie opens a serial port and logs data received to a window. It is...

• Javascript - 448 view I have tried to collect some top spring core interview questionswhich...

• Javascript - 348 view So far in previous tutorials, we have learned about securing your...

• Javascript - 666 view Working with CSV files is not common, but it may be required at times...

• Development Tools - 829 view nteractive analysis is a cycle analysis procedure of assumption,...

• Javascript - 238 view Bing Search API is a set of REST interfaces that find web pages, news,...

• HTML-CSS template - 408 view Pinkrio is a strong and powerful XHTML/CSS template with a clean and...

• PostgreSQL - 1320 view In this article, I want to show some operations in both PostgreSQL &...

• Java mobile - 763 view If you missed the premiere of one of our virtual tech summits you'll...

• Mobile applications - 214 view In this tutorial we will try to create a Simple Image Viewer using...

• Embedded Systems - 1456 view Termie opens a serial port and logs data received to a window. It is...

• Javascript - 448 view I have tried to collect some top spring core interview questionswhich...

• Javascript - 348 view So far in previous tutorials, we have learned about securing your...

• Javascript - 666 view Working with CSV files is not common, but it may be required at times...

• Development Tools - 829 view nteractive analysis is a cycle analysis procedure of assumption,...

• Javascript - 238 view Bing Search API is a set of REST interfaces that find web pages, news,...

• HTML-CSS template - 408 view Pinkrio is a strong and powerful XHTML/CSS template with a clean and...

• PostgreSQL - 1320 view In this article, I want to show some operations in both PostgreSQL &...

• Java mobile - 763 view If you missed the premiere of one of our virtual tech summits you'll...

• Mobile applications - 214 view In this tutorial we will try to create a Simple Image Viewer using...

• Embedded Systems - 1456 view Termie opens a serial port and logs data received to a window. It is...

• Javascript - 448 view I have tried to collect some top spring core interview questionswhich...

• Javascript - 348 view So far in previous tutorials, we have learned about securing your...

• Javascript - 666 view Working with CSV files is not common, but it may be required at times...

• Development Tools - 829 view nteractive analysis is a cycle analysis procedure of assumption,...

• Javascript - 238 view Bing Search API is a set of REST interfaces that find web pages, news,...

• HTML-CSS template - 408 view Pinkrio is a strong and powerful XHTML/CSS template with a clean and...

• PostgreSQL - 1320 view In this article, I want to show some operations in both PostgreSQL &...

• Java mobile - 763 view If you missed the premiere of one of our virtual tech summits you'll...

• Mobile applications - 214 view In this tutorial we will try to create a Simple Image Viewer using...

• Embedded Systems - 1456 view Termie opens a serial port and logs data received to a window. It is...

• Javascript - 448 view I have tried to collect some top spring core interview questionswhich...

• Javascript - 348 view So far in previous tutorials, we have learned about securing your...

• Javascript - 666 view Working with CSV files is not common, but it may be required at times...

• Development Tools - 829 view nteractive analysis is a cycle analysis procedure of assumption,...