Q:

How to sort an array values alphabetically in PHP

0

How to sort an array values alphabetically in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the PHP sort() and rsort() function

The PHP sort() and rsort() functions can be used for sorting numeric or indexed arrays. The following sections will show you how these functions basically work:

Sorting Numeric Arrays in Ascending Order

You can use the sort() function for sorting the numeric array elements or values alphabetically or numerically in the ascending order. Let's try out an example to see how it works:

<?php
$text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon");
$numbers = array(1, 2, 3.5, 5, 8, 10);
 
// Sorting the array of string
sort($text);
print_r($text);
echo "<br>";
 
// Sorting the array of numbers
sort($numbers);
print_r($numbers);
?>

Sorting Numeric Arrays in Descending Order

You can use the rsort() function for sorting the numeric array elements or values alphabetically or numerically in the descending order. Let's check out an example:

<?php
$text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon");
$numbers = array(1, 2, 3.5, 5, 8, 10);
 
// Sorting the array of string
rsort($text);
print_r($text);
echo "<br>";
 
// Sorting the array of numbers
rsort($numbers);
print_r($numbers);
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to remove duplicate values from an array in PH... >>
<< How to merge two or more arrays into one array in ...