brenlei.com

PHP tutorials

Question:

The output of my array (from previous examples), is shown below. How do I sort the array so that it displays in the correct sequence?

Array
(
    [5] => May
    [6] => June
    [7] => July
    [2] => February
)

Answer:

Using the ksort Array function

The ksort array function sorts the array elements in alphabetical/numerical order based on their keys (hence the k in ksort).

<?php
$busy_period = array(5 => 'May', 'June', 'July');
$busy_period[2] = 'February';		//add an element onto the end of the array

ksort($busy_period);	//sort the array on the key index
print_r($busy_period);	//display the contents of the array
unset($busy_period);    //Remove the array from memory
?>
Output
Array
(
    [2] => February
    [5] => May
    [6] => June
    [7] => July
)

Using the asort Array function

The asort array function sorts the array elements in alphabetical/numerical order based on their element values.

<?php
$busy_period = array(5 => 'May', 'June', 'July');
$busy_period[2] = 'February';		//add an element onto the end of the array

asort($busy_period);			//sort the array on the element value
print_r($busy_period);		        //display the contents of the array

//Remove the array from memory
unset($busy_period);
?>
Output
Array
(
    [2] => February
    [7] => July
    [6] => June
    [5] => May
)

Other sort functions

There are the krsort and arsort functions that can be used to sort on the key / element of an array in reverse order.

PHP Reference Manual

array - Creates an array variable

asort - Sort an Array based on element values

ksort - Sort an Array based on Keys

print_r - Prints contents of an array

unset - Deletes a variable

Arrays

Adding Elements to an array with a keyed index
Learn how to add elements to an array that have a key index, or where you need to specify one.

Comments or questions relating to this article have been disabled. They will be back soon.