Sorting an Array

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
)

Using the ksort Array function

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

$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

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.

$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

Output

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

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.