iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Arrays

PHP "arrays" are really ordered maps — they cover both indexed lists and key→value dictionaries with one type.

Two flavours, one type

PHP
// Indexed
$fruits = ['apple', 'banana', 'cherry'];

// Associative
$ages = [
    'Ada'   => 36,
    'Grace' => 56,
    'Linus' => 42,
];

// Mixed (legal, but rarely a good idea)
$mixed = ['a', 1 => 'b', 'key' => 'value'];

Reading & writing

PHP
echo $fruits[0];          // apple
$fruits[] = 'date';        // append
$ages['Margaret'] = 84;    // set

unset($fruits[1]);          // remove banana — leaves a gap in indexed!
echo count($fruits);        // count

Spread & destructure

PHP
$a = [1, 2];
$b = [...$a, 3, 4];           // [1, 2, 3, 4]

[$x, $y]      = [3, 4];        // positional
['a' => $aa]  = ['a' => 1, 'b' => 2]; // associative

Common operations

NeedFunction
Lengthcount($arr)
Loopforeach
Transformarray_map
Filterarray_filter
Reducearray_reduce
Sortsort / rsort / usort / ksort / asort
Keys / valuesarray_keys / array_values
Test membershipin_array / array_key_exists
Tip: PHP arrays are copy-on-write. Passing one to a function is cheap — until the function modifies it. For huge data, prefer iterators / generators.

Example

Example
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $f) {
    echo $f, PHP_EOL;
}
Try it Yourself »

Exercise

Append to an array.

$fruits = 'date';

Test yourself

Q1. PHP arrays are…
Q2. Append with…
Q3. Spread of an array uses…

Discussion

Loading…