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.
Table of Content
Using sort()
Function
The sort()
function is a built-in PHP function that sorts an array in ascending order.
<?php $arr = [5, 2, 8, 3, 1];
// Sort array in ascending order sort( $arr );
// Display the sorted array print_r( $arr );
?> |
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 // 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 );
?> |
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 $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 );
?> |
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 // 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 );
?> |
Array ( [a] => 2 [b] => 5 [d] => 8 )