Tuesday, April 22, 2025

PHP Sorting Arrays

You are advised to check corresponding YouTube video at the end of this article. 


<?php 

$fruits = array("Bananas", "Oranges", "Apples", "Grapes");

echo "BEFORE: <br>";
foreach ($fruits as $x) {
	echo "Element: $x <br>";
}

echo "<br><hr><br>";

sort($fruits);
echo "AFTER: <br>";
foreach ($fruits as $x) {
	echo "Element: $x <br>";
}

?>

This PHP script creates an array of fruits and then sorts the elements in alphabetical order using the sort() function.

The foreach loop is used to display the array elements before and after sorting.

In the first loop, the script prints the elements of the $fruits array as they are stored. In the second loop, the script sorts the $fruits array using the sort() function and then prints the sorted elements.

The output of the script will display the original order of the elements in the array followed by the sorted order of the elements.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...