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
| Need | Function |
|---|---|
| Length | count($arr) |
| Loop | foreach |
| Transform | array_map |
| Filter | array_filter |
| Reduce | array_reduce |
| Sort | sort / rsort / usort / ksort / asort |
| Keys / values | array_keys / array_values |
| Test membership | in_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';
Two characters.
Discussion
Loading…