Tags
Asked 3 years ago
9 Jun 2021
Views 284
Cimb

Cimb posted

Sort array by numerical values in php

how to Sort array by numerical values in php ?
jabber

jabber
answered Apr 27 '23 00:00

To sort an array by numerical values in PHP, you can use the sort() or asort() function depending on whether you want to preserve the original keys or not.

Here is an example of sorting an array of numbers in ascending order using the sort() function:



$myArray = array(5, 3, 9, 2, 8, 1, 4, 6, 7);

sort($myArray);

print_r($myArray);

In this example, we have an array of numbers, and we use the sort() function to sort the array in ascending order. The sort() function modifies the original array, and it sorts the array in place, so we don't need to assign the sorted array to a new variable.

The output of the code will be:



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

If you want to preserve the original keys, you can use the asort() function instead of sort(). Here is an example:



$myArray = array('one' => 1, 'three' => 3, 'nine' => 9, 'two' => 2, 'eight' => 8, 'four' => 4, 'six' => 6, 'seven' => 7);

asort($myArray);

print_r($myArray);

In this example, we have an associative array with numerical values, and we use the asort() function to sort the array by values in ascending order while preserving the keys.

The output of the code will be:



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

As you can see, the array has been sorted by values in ascending order, and the original keys have been preserved.
Post Answer