Sorting arrays in PHP is a common task in web development. You can easily sort arrays in PHP in ascending or descending order using built-in functions like 'sort()' and 'rsort()'. These functions work efficiently on one-dimensional indexed arrays, helping you manage data dynamically. This tutorial covers how to sort arrays in PHP with clear examples for the beginners and developers looking to enhance their PHP skills.
Let's see the code below:
<?php
$languages = array('PHP','C++','Basic','Python','Java');
sort($languages); // sorts array in ascending order
rsort($languages); // sorts array in descending order
Here, we have the array $languages and we are using sort() and rsort() functions on the array. We can use var_dump() to display the new order:
sort()
array(5) { [0]=> string(5) "Basic" [1]=> string(3) "C++" [2]=> string(4) "Java" [3]=> string(3) "PHP" [4]=> string(6) "Python" }
rsort()
array(5) { [0]=> string(6) "Python" [1]=> string(3) "PHP" [2]=> string(4) "Java" [3]=> string(3) "C++" [4]=> string(5) "Basic" }
Now, let us write a program that will display the original and the new array (sorted) in ascending and descending order. We will write html and PHP code to display output in the browser. Let's take a look at the below code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Array Sort Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="text-align: center;font-size: 20px;">
<h3>How to Sort an Array</h3>
<?php
// declare and initialize array
$languages = array('PHP','C++','Basic','Python','Java');
// Display all array element first
echo "Original Array: <strong><br>";
foreach ($languages as $value) {
echo "$value<br>";
}
echo "</strong><br>";
sort($languages); // sorts array in ascending order
echo "Sorted in Ascending Order: <strong><br>";
foreach ($languages as $value) {
echo "$value<br>";
}
echo "</strong><br>";
rsort($languages); // sorts array in descending order
echo "Sorted in Descending Order- : <strong><br>";
foreach ($languages as $value) {
echo "$value<br>";
}
?>
</div>
</body>
</html>
We want to reorder the array $languages in ascending and then descending order. We displayed the original array and then we used sort($languages) to sort it in ascending order. Similarly, by using rsort($languages), we display them in descending order.
Let us save this program as index.php under xampp/htdocs/sort_array folder.
If we run this in the browser using localhost/sort_array, the below output is displayed:
So, this was an example of how to sort an index array in PHP.
Post a Comment