How to use PHP sort() Function In PHP

We will use the built-in sort() function to sort the input array into ascending to descending order. It sorts the actual array and hence changes are reflected in the original array itself. 

Syntax

sort(array &$array, int $sort_flags = SORT_REGULAR): bool

Example: This example uses the built-in sort() function to sort the input array into the correct order.

PHP




<?php
function sortArray($arr)
{
    sort($arr);
    return $arr;
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = sortArray($arr1);
$result2 = sortArray($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>


Output

Sorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

How to Sort an Array containing 1 to n values in PHP ?

In this article, we will see how to sort an array that contains 1 to n values in PHP. There are various approaches through which we can sort an array with custom values. Below is an example for a better understanding of the problem statement.

Example:

Input: arr = [3, 1, 4, 5, 2, 8, 9, 5]
Output: Sorted Array is: [1, 2, 3, 4, 5, 8, 9]
 
Input: arr = [3, 1, 4, 5, 2, 0, 10]
Output: Sorted Array is: [0, 1,  2, 3, 4, 5, 10]

There are two methods to sort an array that contains 1 to n values:

Table of Content

  • Using PHP sort() Function
  • Using a Custom Sorting Algorithm (Bubble Sort)

Similar Reads

Using PHP sort() Function

We will use the built-in sort() function to sort the input array into ascending to descending order. It sorts the actual array and hence changes are reflected in the original array itself....

Using a Custom Sorting Algorithm (Bubble Sort)

...