Quantcast
Channel: AuthorCode » Array in PHP
Viewing all articles
Browse latest Browse all 5

Sorting Arrays in PHP

$
0
0

PHP provides various methods for sorting arrays:sort(), asort(), rsort(), arsort() and ksort(). we will discuss each function one by one.

sort() function

This is commonly used function for sorting arrays. It can be used as :

  1. sort(array_name)

this function sort the array into alphabetical order and then rebuild the index numbers. suppose you have an array like this:

  1. $Capitals[0] = "New Delhi";
  2. $Capitals[2] = "Washington";
  3. $Capitals[1] = "Landon";
  4. $Capitals[5] = "Paris";
  5. $Capitals[4] = "Moscow";
  6. $Capitals[3] = "Tokyo";

you can sort above array as follows:
sort($Capitals);
After sort array will be :

  1. $Capitals[0] = "Landon";
  2. $Capitals[1] = "Moscow";
  3. $Capitals[2] = "New Delhi";
  4. $Capitals[3] = "Paris";
  5. $Capitals[4] = "Tokyo";
  6. $Capitals[5] = "Washington";

asort() function

asort() will also sort the array by its values in alphabetical order, but it will preserve the key
see the following example:

  1. asort($Capitals);

The order would be:

  1. $Capitals[1] = "Landon";
  2. $Capitals[4] = "Moscow";
  3. $Capitals[0] = "New Delhi";
  4. $Capitals[5] = "Paris";
  5. $Capitals[3] = "Tokyo";
  6. $Capitals[2] = "Washington";

rsort() and arsort() function

Both function rsort() and arsort() work in a similar way to sort and asort. The only difference is that they return contents of an array in reverse alphabetical order.

ksort() function

The ksort() function sorts an array by the keys. The values keep their original keys.
See the following array:

  1. $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
  2. ksort($fruits);

The order would be:

  1. $fruits[a] = orange
  2. $fruits[b] = banana
  3. $fruits[c] = apple
  4. $fruits[d] = lemon

Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images