What is the purpose of the PHP sort function?

The sort() function in PHP is an array sorting function used to sort arrays in ascending order. It can sort both indexed arrays and associative arrays.

Specifically, the sort() function will alter the original array and rearrange it in ascending order. The sorted array will be reassigned indexes based on the values of the elements, starting from 0 and increasing incrementally.

The sort() function can be used in the following scenarios:

  1. Sort the array of numbers: rearrange the numbers in ascending order.
  2. Sort the array of strings in alphabetical order.
  3. Sort an array of mixed types: arrange the elements in the array based on specific rules, such as placing numbers before strings.

Below is an example of sorting an array using the sort() function.

$numbers = array(4, 2, 8, 6);
sort($numbers);

print_r($numbers);

The output result is: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

Please note that the sort() function will change the original order of the array, so it is recommended to first make a copy before sorting if you need to preserve the original array.

bannerAds