Menu
Coddy logo textTech

Sort Indexed Arrays Ascending

Part of the Logic & Flow section of Coddy's PHP journey — lesson 20 of 68.

When you need to organize data in a logical order, PHP's sort() function provides a simple way to arrange indexed arrays in ascending order. Whether you're working with numbers or strings, this function automatically sorts elements from smallest to largest or alphabetically from A to Z.

Here's how sort() works with a basic array of numbers:

<?php
$numbers = [45, 12, 78, 23, 56];
sort($numbers);
print_r($numbers);
// Outputs: Array ( [0] => 12 [1] => 23 [2] => 45 [3] => 56 [4] => 78 )
?>

An important characteristic of sort() is that it modifies the original array directly, rather than creating a new sorted copy. This means after calling sort(), your original array is permanently changed to reflect the new order.

The function works equally well with strings, sorting them alphabetically. This makes sort() particularly useful for organizing lists of names, organizing inventory items, or preparing data for display in a user-friendly format.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You will receive one input: an array of test scores in JSON format. Read the input, convert the JSON string to an array, use sort() to arrange the scores in ascending order, and print the sorted array using print_r().

Input format: One line containing a JSON array of numbers (example: [78,92,65,88,71])

Expected output: The sorted array in ascending order, displayed using print_r()

Cheat sheet

The sort() function arranges indexed arrays in ascending order (smallest to largest for numbers, A to Z for strings):

<?php
$numbers = [45, 12, 78, 23, 56];
sort($numbers);
print_r($numbers);
// Outputs: Array ( [0] => 12 [1] => 23 [2] => 45 [3] => 56 [4] => 78 )
?>

Important: sort() modifies the original array directly rather than creating a new sorted copy.

Try it yourself

<?php
// Read input
$input = trim(fgets(STDIN));

// Convert JSON string to array
$scores = json_decode($input, true);

// TODO: Write your code below to sort the array


// Output the sorted array
print_r($scores);
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow