PASSWORD RESET

Your destination for complete Tech news

PHP

How to sort array values alphabetically in PHP?

473 0
< 1 min read

To sort an array alphabetically in PHP, you can use the sort() function. This function sorts an array in ascending order, and assigns the sorted values to the original array.

For example:

$fruits = array('cherry', 'apple', 'banana');

sort($fruits);

foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

This would output:

0 = apple
1 = banana
2 = cherry

If you want to sort the array in descending order, you can use the rsort() function.

If you want to preserve the keys of the array, you can use the asort() function to sort the array by the values, or the ksort() function to sort the array by the keys.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.