Introduction:
Welcome to our in-depth guide on PHP array sorting! Arrays are fundamental data structures in PHP, and the ability to efficiently sort them is crucial for any web developer. In this lesson, we’ll explore various PHP functions for sorting arrays, including examples and practical applications. By the end, you’ll have a solid understanding of sorting techniques to enhance your PHP programming skills.
In PHP, you can sort arrays using various functions depending on your specific requirements. Here are some commonly used functions for sorting arrays:
This function sorts an array in ascending order. It modifies the original array.
$numbers = array(4, 2, 8, 6); sort($numbers); print_r($numbers);
Output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
This function sorts an array in descending order. It modifies the original array.
$numbers = array(4, 2, 8, 6); rsort($numbers); print_r($numbers);
Output:
Array
(
[0] => 8
[1] => 6
[2] => 4
[3] => 2
)
This function sorts an associative array by values in ascending order. It maintains the key-value associations.
$ages = array("Omar" => 20, "Gogo" => 17, "Adam" => 5); asort($ages); print_r($ages);
Output:
Array
(
[Gogo] => 17
[Omar] => 20
[Adam] => 5
)
$ages = array("Omar" => 20, "Gogo" => 17, "Adam" => 5); arsort($ages); print_r($ages);
Output:
Array
(
[Adam] => 5
[Omar] => 20
[Gogo] => 17
)
This function sorts an associative array by keys in ascending order.
$ages = array("Omar" => 20, "Gogo" => 17, "Adam" => 5); ksort($ages); print_r($ages);
Output:
Array
(
[Adam] => 5
[Gogo] => 17
[Omar] => 20
)
This function sorts an associative array by keys in descending order.
$ages = array("Omar" => 20, "Gogo" => 17, "Adam" => 5); krsort($ages); print_r($ages);
Output:
Array
(
[Omar] => 20
[Gogo] => 17
[Adam] => 5
)
These functions provide a flexible way to sort arrays in PHP based on different criteria. Choose the appropriate function depending on whether you want to sort in ascending or descending order and whether you want to maintain key-value associations in associative arrays.
complete example in html with explanation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Array Sorting Example</title> </head> <body> <?php // Define an associative array with names and ages $ages = array("Omar" => 20, "Gogo" => 17, "Adam" => 5); // Display the unsorted array echo "<h2>Unsorted Array</h2>"; print_r($ages); // Sort the array by values in ascending order asort($ages); // Display the sorted array echo "<h2>Sorted Array (Ascending Order)</h2>"; print_r($ages); ?> </body> </html>
Explanation:
Defining the Associative Array:
$ages = array(“Omar” => 20, “Gogo” => 17, “Adam” => 5);
We define an associative array named $ages with names as keys and ages as values.
Displaying the Unsorted Array:
echo “<h2>Unsorted Array</h2>”;
print_r($ages);
This part displays the unsorted array using print_r() to show the initial order.
Sorting the Array:
asort($ages);
The asort() function is used to sort the array by values in ascending order.
Displaying the Sorted Array:
echo “<h2>Sorted Array (Ascending Order)</h2>”;
print_r($ages);
Finally, we display the sorted array to show the result.
When you open this HTML file in a web browser and view the page source, you will see the initial unsorted array and the array after sorting. The names will be sorted based on their corresponding ages in ascending order.
create an application by this lesson with explanation
Create a file named index.php with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Array Sorting Application</title> <style> body { font-family: Arial, sans-serif; } form { margin-bottom: 20px; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <?php // Initialize an empty associative array $ages = array(); // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get input $name = $_POST["name"]; $age = $_POST["age"]; // Add the input to the associative array $ages[$name] = $age; } // Display the form echo "<form method='post'> <label for='name'>Name:</label> <input type='text' name='name' required> <label for='age'>Age:</label> <input type='number' name='age' required> <button type='submit'>Add Person</button> </form>"; // Display the unsorted array echo "<h2>Unsorted Array</h2>"; if (empty($ages)) { echo "<p>No data available.</p>"; } else { displayArray($ages); } // Sort the array by values in ascending order asort($ages); // Display the sorted array echo "<h2>Sorted Array (Ascending Order)</h2>"; if (empty($ages)) { echo "<p>No data available.</p>"; } else { displayArray($ages); } // Function to display the array in a table function displayArray($array) { echo "<table> <tr> <th>Name</th> <th>Age</th> </tr>"; foreach ($array as $name => $age) { echo "<tr> <td>$name</td> <td>$age</td> </tr>"; } echo "</table>"; } ?> </body> </html>
Explanation:
Form Handling:
The form in the HTML allows s to input names and ages. When the form is submitted, the PHP code checks if the request method is POST and retrieves the input values.
The input values are then added to the associative array $ages.
Displaying Arrays:
The displayArray function is created to generate an HTML table displaying the names and ages in a clear format.
Both the unsorted and sorted arrays are displayed using this function.
Styling:
Some basic CSS styles are applied to make the application visually appealing.
When you open index.php in a web browser, you’ll see a form to input names and ages. The application will display the unsorted array first, and after submitting the form, it will display the sorted array in ascending order based on the ages.
Below is a quiz about PHP array sorting. Each question has multiple-choice answers, and the correct answer is indicated.
PHP Array Sorting Quiz
a. Sorts an array in descending order
b. Sorts an array in ascending order
c. Sorts an associative array by keys
d. None of the above
Correct Answer: b. Sorts an array in ascending order
a. ksort()
b. rsort()
c. asort()
d. sort()
Correct Answer: b. rsort()
a. Sorts an array in ascending order by keys
b. Sorts an array in descending order by values
c. Sorts an associative array in ascending order by values
d. None of the above
Correct Answer: c. Sorts an associative array in ascending order by values
a. sort()
b. rsort()
c. asort()
d. arsort()
Correct Answer: c. asort()
a. krsort()
b. ksort()
c. arsort()
d. asort()
Correct Answer: a. krsort()
a. rsort()
b. arsort()
c. asort()
d. sort()
Correct Answer: b. arsort()
a. Sorts an array in descending order by keys
b. Sorts an array in ascending order by values
c. Sorts an associative array in ascending order by keys
d. Sorts an array in descending order by values
Correct Answer: c. Sorts an associative array in ascending order by keys
a. ksort()
b. krsort()
c. asort()
d. arsort()
Correct Answer: a. ksort()
a. Sorts an array in descending order
b. Sorts an associative array by values in ascending order
c. Sorts an array in ascending order
d. Sorts an associative array by values in descending order
Correct Answer: d. Sorts an associative array by values in descending order
a. sort()
b. rsort()
c. asort()
d. arsort()
Correct Answer: a. sort()
a. showArray()
b. displayArray()
c. printArray()
d. echoArray()
Correct Answer: b. displayArray()
a. GET
b. POST
c. SUBMIT
d. METHOD
Correct Answer: b. POST
a. To sort the array
b. To add elements to the array
c. To display the array in a table format
d. To remove elements from the array
Correct Answer: c. To display the array in a table format
a. To check if the array is sorted
b. To check if the array is empty
c. To check if the array is associative
d. To check if the array is numeric
Correct Answer: b. To check if the array is empty
a. sortedArray()
b. sortArray()
c. sort()
d. sorted()
Correct Answer: c. sort()