Google News
logo
PHP Program to sort() - Sort array in ascending alphabetical order
In the following example of PHP program that demonstrates how to use the `sort()` function to sort an array of strings in ascending alphabetical order :
Program :
<?php

// Create an array of strings
$fruits = array("banana", "apple", "orange", "mango");

// Sort the array in ascending alphabetical order
sort($fruits);

// Loop through the sorted array and print the values
foreach($fruits as $fruit) {
    echo $fruit . "<br>";
}

?>
Output :
apple
banana
mango
orange
In this example, we have created an array of strings `$fruits` containing the names of some fruits. We use the `sort()` function to sort the array in ascending alphabetical order. The sorted array is then looped through using a `foreach` loop and the values of each element are printed to the screen.

The `sort()` function works by comparing the values of the elements in the array and swapping them if necessary to put them in ascending order. It modifies the original array in place and returns a boolean value indicating whether the sort was successful or not.

Note that when sorting an array of strings, `sort()` uses a case-sensitive comparison by default. If you want to sort the array in a case-insensitive manner, you can use the `natcasesort()` function instead.