</>
Skip to content
PHP lessons (20/49)

PHP — Sorting Arrays

Creating arrays

PHP offers two syntaxes:

<?php
// array() function
$fruits = array("Apple", "Banana", "Cherry");

// Short syntax (preferred)
$colors = ["Red", "Green", "Blue"];

// Empty array
$empty = [];

// With range
$numbers = range(1, 10); // [1, 2, 3, ..., 10]
?>

Indexed arrays

Numerically indexed, starting from 0:

<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo $fruits[0];    // Apple
echo $fruits[1];    // Banana
echo count($fruits); // 3

// Add to end
$fruits[] = "Date"; // Append

// Add at index
$fruits[10] = "Fig"; // Sparse array — indices 3-9 are empty
?>

Associative arrays

String keys for labeled data:

<?php
$person = [
    "name" => "Alice",
    "age" => 30,
    "email" => "alice@example.com"
];

echo $person["name"];   // Alice
echo $person["age"];    // 30

// Add new key-value pair
$person["phone"] = "555-1234";
?>

Multidimensional arrays

Arrays within arrays:

<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

echo $matrix[1][2]; // 6

$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob", "age" => 25],
    ["name" => "Charlie", "age" => 35]
];

echo $users[0]["name"]; // Alice
?>

Common array functions

<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Size and presence
echo count($fruits);             // 3
echo in_array("Banana", $fruits); // true

// Search
$key = array_search("Cherry", $fruits); // 2
echo array_key_exists("name", $person); // true

// Add and remove
$fruits[] = "Date";              // Append to end
array_push($fruits, "Elder");    // Push to end
$last = array_pop($fruits);      // Remove from end
$first = array_shift($fruits);   // Remove from beginning
array_unshift($fruits, "Fig");   // Add to beginning

// Sort
sort($fruits);                   // Sort ascending
rsort($fruits);                  // Sort descending
asort($fruits);                  // Sort by value, keep keys
ksort($fruits);                  // Sort by key
usort($fruits, fn($a, $b) => strlen($a) <=> strlen($b)); // Custom sort
?>

Array transformation

<?php
$numbers = [1, 2, 3, 4, 5];

// Map: transform each element
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($doubled); // [2, 4, 6, 8, 10]

// Filter: keep elements matching a condition
$evens = array_filter($numbers, fn($n) => $n % 2 == 0);
print_r($evens); // [2, 4]

// Reduce: accumulate into a single value
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo $sum; // 15

// Flip keys and values
$flipped = array_flip(["a" => 1, "b" => 2]);
print_r($flipped); // [1 => "a", 2 => "b"]
?>

Slicing and combining

<?php
$numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

// Slice
$slice = array_slice($numbers, 2, 3); // [2, 3, 4]
$lastThree = array_slice($numbers, -3); // [7, 8, 9]

// Merge
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b); // [1, 2, 3, 4, 5, 6]

// Combine keys and values
$keys = ["name", "age", "email"];
$values = ["Alice", 30, "alice@example.com"];
$person = array_combine($keys, $values);
print_r($person);
// [name => Alice, age => 30, email => alice@example.com]

// Fill
$zeros = array_fill(0, 5, 0); // [0, 0, 0, 0, 0]

// Chunk
$chunked = array_chunk($numbers, 3);
print_r($chunked);
// [[0,1,2], [3,4,5], [6,7,8], [9]]
?>

Destructuring arrays

<?php
// List syntax
$colors = ["Red", "Green", "Blue"];
list($first, $second, $third) = $colors;
echo "$first, $second, $third"; // Red, Green, Blue

// Short syntax (PHP 7.1+)
[$a, $b, $c] = [1, 2, 3];

// Skip elements
[, $second, $third] = ["a", "b", "c"];
echo "$second, $third"; // b, c

// Associative destructuring
["name" => $name, "age" => $age] = ["name" => "Alice", "age" => 30];
echo "$name is $age"; // Alice is 30
?>

Spread operator

<?php
// Unpack arrays
$a = [1, 2];
$b = [3, 4];
$combined = [...$a, ...$b]; // [1, 2, 3, 4]

// Function arguments
$numbers = [3, 1, 4, 1, 5];
$max = max(...$numbers); // 5
$sum = array_sum($numbers); // 14

// Copy
$copy = [...$numbers];
?>

Mini Practice

Write PHP code that:

  1. Creates an associative array of 5 products with prices
  2. Filters products that cost more than $10
  3. Uses array_map to apply a 10% discount to all prices
  4. Destructures the first two elements of an indexed array

Up Next

In the next lesson, you'll learn about Functions — defining, calling, and working with function parameters.

Related Topics

Frequently Asked Questions about Sorting Arrays

What is Sorting Arrays in PHP?

Sorting Arrays is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Sorting Arrays?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sorting Arrays.

Why is Sorting Arrays important in PHP?

Sorting Arrays is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.