In PHP, how do I sort arrays for beginners?

In PHP, sorting arrays can be easily achieved using built-in functions. Here are some common methods to sort arrays:

  • sort() - Sorts an array in ascending order.
  • rsort() - Sorts an array in descending order.
  • asort() - Sorts an associative array in ascending order, according to the value.
  • ksort() - Sorts an associative array in ascending order, according to the key.
  • usort() - Sorts an array by values using a user-defined comparison function.

Here is a simple example of how to sort a numeric array in PHP:

<?php $numbers = array(3, 2, 5, 1, 4); sort($numbers); print_r($numbers); ?>

This example will output:

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

PHP sort arrays PHP arrays PHP sort function sort array example