Home  >  Article  >  Backend Development  >  Sorting in PHP

Sorting in PHP

WBOY
WBOYOriginal
2024-08-29 13:04:46303browse

Sorting is to arrange the elements of an array in a particular order. PHP performs sorting on normal arrays like a numeric array and on associative arrays. Normal arrays like numeric arrays can be sorted by using the simple sort() function, and to perform the sorting on the associative array, we have different functions.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The sorting can be done in ascending or descending order, alphabetical or numerical order, natural way, random and also user-defined order. For arrays like the numeric array or indexed array and for associative arrays, sorting is done in ascending order or descending array based on key or based on the value in any of the two orders like the ascending or descending order. Sorting on arrays makes your search easier if the data elements are in sorted form.

How Sorting is Performed in PHP?

Sorting is performed in PHP using sort functions. There are a variety of sort functions.

Suppose you want to know the age of members of a family based on seniority. There may be 15 members in a family. To sort the age of 15 members, we use the sort function and get the result quickly. Thus, in such a case, sort comes into the picture and is preferable.

Also, there is no need to use any libraries.

Syntax:

sort(array);

where an array is the name of the input array.

The following example sorts the elements of the $people and $ages array.

Sort in Alphabetical Order:

$people = array ('Rama', 'James', 'Mary', 'Alice', 'Radha');

Sort in Numerical Order:

$ages = array (25,10,30,15,20);

Combining the above two arrays and creating one associative.

$people_ages = array ('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);

Sort in Numerical Order with Example:

Code:

<?php
//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
} ?>

Output :

Sorting in PHP

Sort in Alphabetical Order with Example:

Code:

<?php
//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}
?>

Output :

Sorting in PHP

Sorting an Associative Array

Performing sort on associative arrays which have key-value pair association will end up in the lost of the keys. Also though the sort is performed, each element of the array now has been assigned a new numeric index.

Code:

// example to perform sort on people and ages array together
// you will find that the keys are not preserved and changed
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting we will use foreach loop
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach ($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

And thus, instead of a simple sort(), we use asort(). asort() is a function that sorts the elements of an associative array in ascending order. And arsort() is a function that sorts the elements of an array in descending order. Both are sorted by value. Now let us learn about these array along with other array functions in detail

Types of Sorting in PHP

The different types of array functions are mentioned below, along with the order of sort, whether it is in ascending or descending order and the function sorts by either key or sorts by value are also mentioned.

  • sort(): this function sorts the input array in ascending order and sorts it by value
  • rsort(): this function sorts the input array in descending order and sorts it by value
  • asort(): this function sorts the input array in ascending order and sorts it by value
  • arsort(): this function sorts the input array in descending order and sorts by value
  • ksort(): this function sorts the input array in ascending order and sorts it by key
  • krsort(): this function sorts the input array in descending order and sorts it by key
  • usort(): this function sorts the input array based on the user-defined function and sorts by value
  • uasort(): this function sorts the input array based on the user-defined function and sorts by value
  • uksort(): this function sorts the input array based on the user-defined function and sorts by key
  • natsort(): this function sorts the input array-based natural ordering.
  • natcasesort(): this function sorts the input array-based natural ordering and is case insensitive.
  • shuffle(): this function sorts the input array based on the value, and the output is a random order of values.

Let us learn about each function in detail

1. sort()

This function we have already seen. This function performs sorting on the given array and arranges the elements of the array in ascending array.

Code :

//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}

Output:

Sorting in PHP

2. rsort()

This function performs sorting on the given array and arranges the elements of the array in descending array, opposite of what sort() function does. Also, the sorting is performed with values.

a. Code:

//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}

Output :

Sorting in PHP

b. Code:

//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}

Output:

Sorting in PHP

3. asort()

This function performs sorting on the given array and arranges the array’s values in ascending order, opposite of what sort() function does. Also, the sorting is performed with values and not keys.

Code :

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
asort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

4. arsort()

This function performs sorting on the given array and arranges the array’s values in a descending array. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
arsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

5. ksort()

This function performs sorting on the given array and arranges the keys of the array in ascending order. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
ksort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

6. krsort()

This function performs sorting on the given array and arranges the keys of the array in descending order. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
krsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

7. natsort()

This function performs sorting on the given array and arranges the keys of the array in descending order. This example prints the array using a foreach loop and outputs the result as before sorting using assort() function and after sorting using natsort() function.

This function refreshes the output as the function randomizes the order of values in the given array. New numeric keys replace the keys mentioned in the array are assigned. For example, 10 is greater than 7 in a human being view, but according to the sorting algorithm 10 comes before 7.

We will use the natural flow of order.

Code:

<?php
$input = array("13 orange","14 Apple","15 3Banana","11 papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
//array before sorting
foreach($arr1 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natsort($arr2);
echo "Using natsort function "."<br>";
foreach($arr2 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
?>

Output :

Sorting in PHP

8. natcasesort()

This function works the same as natsort() but is case insensitive.

Code:

$input = array("13 orange","14 Apple","15 Banana","11 papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
//array before sorting
foreach($arr1 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natcasesort($arr2);
echo "Using natcasesort function "."<br>";
foreach($arr2 as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output :

Sorting in PHP

9. usort()

This function performs sorting on the given array and arranges the values of the array in ascending order. This example prints the array using for loop and outputs the result.

In this program, the usort function takes two parameters: the input array and the other is the name of the function being called (here is compare).

This compare function is user-defined; also, the function is optional. This function returns 0 only if the condition in if block is satisfied, and else it will send -1 if the values compared is smaller than the other and 1 if the values compared is greater than the other.

Code:

function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
$numbers = array(10,4,5,3,20);
echo "Before Sort"."<br>";
//array after sorting
$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}
echo '<hr>';
//performing sort
usort($numbers, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}

Output :

Sorting in PHP

10. uasort()

This function performs sorting on the given array and arranges the array’s values in ascending order using the compare function.

Code:

<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
echo '<hr>';
//performing sort
$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5, "num5"=>20);
uasort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

11. uksort()

This function performs sorting on the given array and arranges the array’s keys in ascending order using the compare function.

Code:

<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
echo '<hr>';
//performing sort
$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5, "num5"=>20);
uksort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output :

Sorting in PHP

12. shuffle()

This function refreshes the output as the function randomizes the order of values in the given array. New numeric keys replace the keys mentioned in the array are assigned.

Code:

$input = array('a'=>"Guava",'e'=>"Apple",'b'=>"Orange",'c'=>"Papaya", 'd' => "Banana");
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
shuffle($input);
echo 'You need to refresh to see the new shuffle everytime'.'<br>';
$array_length = count($input);
echo '<hr>';
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}

Output:

Sorting in PHP

Conclusion

In this article, most of the types of sorting are covered. The arrays are explained with examples. I hope you find it useful, informative and interesting.

The above is the detailed content of Sorting in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP Form ValidationNext article:PHP Form Validation