0
0
PHPprogramming~15 mins

Array sort functions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Array sort functions
📖 Scenario: You have a list of fruits with their prices. You want to organize this list in different ways to find the cheapest or most expensive fruits easily.
🎯 Goal: Learn how to use PHP array sort functions to sort an associative array by keys and values in ascending and descending order.
📋 What You'll Learn
Create an associative array with fruit names as keys and prices as values.
Create a variable to hold the sorted array.
Use PHP array sort functions to sort the array by values ascending and descending.
Use PHP array sort functions to sort the array by keys ascending and descending.
Print the sorted arrays to see the results.
💡 Why This Matters
🌍 Real World
Sorting arrays is useful when you want to organize data like product prices, names, or scores to find the best or worst quickly.
💼 Career
Knowing how to sort arrays is a basic skill for web developers and programmers who handle data and need to display it in a user-friendly order.
Progress0 / 4 steps
1
Create the fruits array
Create an associative array called fruits with these exact entries: 'Apple' => 3, 'Banana' => 1, 'Cherry' => 2, 'Date' => 5, 'Elderberry' => 4.
PHP
Need a hint?

Use square brackets [] to create the array and separate each fruit and price with commas.

2
Create a variable for sorted array
Create a variable called sortedFruits and set it equal to $fruits to prepare for sorting.
PHP
Need a hint?

Assign the existing array $fruits to a new variable $sortedFruits so you can sort it without changing the original.

3
Sort the array by values ascending
Use the PHP function asort() on $sortedFruits to sort the array by values in ascending order.
PHP
Need a hint?

Use asort() to sort the array by its values while keeping the keys.

4
Print the sorted array
Print the $sortedFruits array using print_r() to display the sorted fruits by price ascending.
PHP
Need a hint?

Use print_r() to show the array structure and values clearly.