Open In App

PHP Program to Sort an Array in Ascending Order

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting array elements is a common operation in programming. PHP provides several methods to achieve this operation. In this article, we will explore various approaches to sort array elements of an array in ascending order.

Using sort() Function

The sort() function is a built-in PHP function that sorts an array in ascending order.

PHP




<?php
  
$arr = [5, 2, 8, 3, 1];
  
// Sort array in ascending order
sort($arr);
  
// Display the sorted array
print_r($arr);
  
?>


Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 8
)

Using asort() Function

The asort() function is similar to sort(), but it maintains the association between keys and values.

PHP




<?php
  
// Associative array
$arr = ['b' => 5, 'a' => 2, 'd' => 8];
  
// Sort array by values in
// ascending order
asort($arr);
  
// Display the sorted array
print_r($arr);
  
?>


Output

Array
(
    [a] => 2
    [b] => 5
    [d] => 8
)

Using array_multisort() Function

The array_multisort() function is used to sort multiple arrays or a multi-dimensional array.

PHP




<?php
  
$names = ['John', 'Anna', 'Bob'];
$ages = [30, 25, 35];
  
// Sorting arrays based on the 
// values in the first array
array_multisort($names, $ages);
  
// Displaying the sorted arrays
print_r($names);
print_r($ages);
  
?>


Output

Array
(
    [0] => Anna
    [1] => Bob
    [2] => John
)
Array
(
    [0] => 25
    [1] => 35
    [2] => 30
)

Using uasort() Function with Custom Comparison Function

The uasort() function enables sorting an associative array using a user-defined comparison function.

PHP




<?php
  
// Associative array
$arr = ['b' => 5, 'a' => 2, 'd' => 8];
  
// Sort array using a custom 
// comparison function
uasort($arr, function ($a, $b) {
    return $a - $b;
});
  
// Display sorted array
print_r($arr);
  
?>


Output

Array
(
    [a] => 2
    [b] => 5
    [d] => 8
)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads