• Post category:PHP

How to Sort Array Alphabetically in PHP

PHP Sort Array Alphabetically

To sort the php array alphabetically, we need to use the sort() function. PHP comes with a number of built-in functions designed for sorting array elements in different ways. The first of these is the sort() function, which sorts numerically indexed arrays alphabetically or numerically, from lowest to highest value. For example, see the above code.

Ex:

<?php
$arr= array("Moon", "Water", "Ball", "Apple", "Run", "Desert", "Sun");
sort($arr);
print_r($arr);
?>

Output:

sort() function in PHP

  1. Here, we have created an array in the variable “$arr” and it has some string values.
  2. I want to sort alphabetic order from A to Z, for that we need to use the PHP sort() function and pass the array name as a value.
  3. Then print the array. See the above output the array is perfectly sorted in alphabetic order.

Leave a Reply