Data Structures

Arrays

Work with PHP's powerful array type — indexed, associative, and multidimensional arrays.

PHP Arrays

PHP arrays are extremely versatile. A single array can hold strings, integers, objects — even other arrays.

Types of Arrays

  • Indexed arrays: Numeric keys (0, 1, 2...)
  • Associative arrays: String keys (like dictionaries/maps)
  • Multidimensional arrays: Arrays containing arrays

Array Functions

PHP has hundreds of array functions. The most commonly used include:

array_push, array_pop, array_shift, array_unshift, count, array_merge, array_slice, in_array, array_search, array_keys, array_values, sort, usort, array_map, array_filter

Example

php
<?php
// Indexed array
$fruits = ["apple", "banana", "cherry"];
$fruits[] = "date";        // append
echo $fruits[0];           // apple
echo count($fruits);       // 4

// Associative array
$person = [
    "name" => "Alice",
    "age"  => 30,
    "city" => "Paris",
];
echo $person["name"];  // Alice

// Add/update
$person["email"] = "alice@example.com";

// Check if key exists
if (isset($person["email"])) {
    echo "Email: " . $person["email"];
}

// Loop over indexed
foreach ($fruits as $fruit) {
    echo $fruit . "
";
}

// Loop over associative
foreach ($person as $key => $value) {
    echo "$key: $value
";
}

// Array functions
$nums = [3, 1, 4, 1, 5, 9, 2, 6];
sort($nums);                        // sort in place
$unique = array_unique([1,2,2,3]); // [1,2,3]
$doubled = array_map(fn($n) => $n * 2, $nums);
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
$sum = array_sum($nums);           // sum all values

// Multidimensional
$users = [
    ["name" => "Alice", "score" => 95],
    ["name" => "Bob",   "score" => 87],
];
echo $users[0]["name"];  // Alice
Try it yourself — PHP