One structure for everything
Most languages give you several containers: a list, a dictionary, a set, a tuple. PHP gives you one, the array, and asks it to do all those jobs. A PHP array is an ordered map: a collection of key-value pairs that remembers the order in which keys were inserted. A list is just an array whose keys happen to be 0, 1, 2 and so on; a dictionary is an array with string keys; a row from a database is an array with column names as keys; a JSON object decoded with json_decode($s, true) is an array too.
This is wonderfully convenient and occasionally treacherous. Because lists and maps are the same thing, an operation that removes elements from a list can quietly turn it into a map with gaps in its keys, and that matters the moment you encode it as JSON or pass it to code that expects 0, 1, 2. This lesson shows you both the convenience and the traps, then turns to strings, which in PHP are sequences of bytes, with all that implies for text in the world's languages.
In larger programs, professional PHP code often moves from loose arrays to small classes with typed properties (the next lessons), because a class says exactly which fields exist. But arrays remain the everyday tool for lists of things and for data on its way in and out.
Keys, values and order
<?php
declare(strict_types=1);
// A list: keys 0, 1, 2 … in order.
$cities = ["Accra", "Quito", "Hanoi"];
$cities[] = "Tbilisi"; // append
echo count($cities), " cities, the second is $cities[1]\n";
// A map: string keys, still in insertion order.
$population = ["Accra" => 2.6, "Quito" => 2.0];
$population["Hanoi"] = 8.4;
foreach ($population as $city => $millions) {
echo "$city: {$millions}M\n";
}
// Keys are converted: "7" becomes the integer 7, true becomes 1.
$odd = ["7" => "a", 7 => "b", true => "c", "07" => "d"];
var_dump($odd);
// Removing an element leaves a gap: the array is no longer a list.
unset($cities[1]);
var_dump(array_is_list($cities), array_keys($cities));
$cities = array_values($cities); // renumber 0, 1, 2
var_dump(array_is_list($cities));
// Destructuring, by position and by key.
[$first, , $third] = $cities;
["Accra" => $accra, "Hanoi" => $hanoi] = $population;
echo "$first, $third; $accra, $hanoi\n";
[$a, $b] = [1, 2];
[$a, $b] = [$b, $a]; // swap
echo "a=$a b=$b\n";4 cities, the second is Quito
Accra: 2.6M
Quito: 2M
Hanoi: 8.4M
array(3) {
[7]=>
string(1) "b"
[1]=>
string(1) "c"
["07"]=>
string(1) "d"
}
bool(false)
array(3) {
[0]=>
int(0)
[1]=>
int(2)
[2]=>
int(3)
}
bool(true)
Accra, Tbilisi; 2.6, 8.4
a=2 b=1The rules, precisely:
- Keys are integers or strings, nothing else. A string that is a canonical decimal integer, such as
"7", is converted to the integer 7, so"7"and7are the same key and the later value ("b") wins."07"is not canonical, so it stays a string.truebecomes 1. (Float keys are truncated, with a deprecation notice since 8.1.) - Order is insertion order, not key order.
$a[] = $xappends with the key one larger than the largest integer key so far. unsetremoves a key without renumbering. After removing index 1, the keys are 0, 2, 3, andarray_is_list(PHP 8.1) says it is no longer a list.array_valuesrenumbers. This matters for JSON:json_encodewrites a list as a JSON array[…]but a gappy array as an object{"0": …, "2": …}, which can break the code that receives it.- Destructuring unpacks an array into variables, by position (skip one with an empty slot) or by key. Swapping two variables with
[$a, $b] = [$b, $a]is idiomatic.
Inside a double-quoted string, $cities[1] works for a simple index, but anything more (a string key, a method call, a property of a property) needs braces: "{$items['tea']}", "{$user->name}".
Working with arrays of records
Here is the kind of data you meet every day: a list of rows, each an associative array. The standard library has a function for most things you want to do with it.
<?php
declare(strict_types=1);
$sales = [
["seller" => "Ngozi", "item" => "mangoes", "kg" => 12, "price" => 150],
["seller" => "Diego", "item" => "potatoes", "kg" => 30, "price" => 45],
["seller" => "Ngozi", "item" => "yams", "kg" => 8, "price" => 220],
["seller" => "Leila", "item" => "dates", "kg" => 5, "price" => 600],
["seller" => "Diego", "item" => "maize", "kg" => 20, "price" => 35],
];
// Add a computed field to every row.
$sales = array_map(fn(array $s): array => [...$s, "total" => $s["kg"] * $s["price"]], $sales);
// Keep the big sales. array_filter keeps the original keys!
$big = array_filter($sales, fn(array $s): bool => $s["total"] >= 1750);
echo "big sales at keys: ", implode(", ", array_keys($big)), "\n";
// One column, and a sum.
echo "items: ", implode(", ", array_column($sales, "item")), "\n";
echo "revenue: ", array_sum(array_column($sales, "total")), "\n";
// Group by seller with a plain loop: often the clearest way.
$bySeller = [];
foreach ($sales as $s) {
$bySeller[$s["seller"]] = ($bySeller[$s["seller"]] ?? 0) + $s["total"];
}
arsort($bySeller); // sort by value, descending, keeping keys
print_r($bySeller);
// Sort rows by kilograms, then name (usort is stable since PHP 8.0).
usort($sales, fn(array $x, array $y): int => [$y["kg"], $x["item"]] <=> [$x["kg"], $y["item"]]);
echo "by weight: ", implode(" > ", array_column($sales, "item")), "\n";
// PHP 8.4 and 8.5 helpers.
$firstExpensive = array_find($sales, fn(array $s): bool => $s["price"] > 200);
echo "first over 200: ", $firstExpensive["item"], "\n";
var_dump(array_any($sales, fn($s) => $s["kg"] > 25), array_all($sales, fn($s) => $s["kg"] > 1));
echo "first and last item: ", array_first($sales)["item"], ", ", array_last($sales)["item"], "\n";
echo "total kg: ", array_reduce($sales, fn(int $carry, array $s): int => $carry + $s["kg"], 0), "\n";big sales at keys: 0, 2, 3
items: mangoes, potatoes, yams, dates, maize
revenue: 8610
Array
(
[Ngozi] => 3560
[Leila] => 3000
[Diego] => 2050
)
by weight: potatoes > maize > mangoes > yams > dates
first over 200: yams
bool(true)
bool(true)
first and last item: potatoes, dates
total kg: 75What each tool does, and the details people trip over:
array_map($fn, $array)returns a new array of$fnapplied to each value. Note the argument order: the callback comes first here but second inarray_filterandarray_reduce, one of PHP's famous inconsistencies.[...$s, "total" => …]spreads the old row into a new one and adds a key.array_filter($array, $fn)keeps the elements for which$fnreturns true, with their original keys: here 0, 2 and 3. Wrap it inarray_values(...)when you need a list again.array_column($rows, "item")pulls one field out of every row; with a third argument it can also choose the keys.- Grouping has no single built-in function. A
foreachwith??to start each group at zero is short, fast, and what most PHP developers write. - Sorting functions sort in place and return
true, not the sorted array:sortandrsortfor values (renumbering keys),asortandarsortto sort by value but keep keys,ksortandkrsortby key, andusort,uasort,uksortwith your own comparison. Comparing two arrays with<=>compares element by element, which makes multi-key sorts one line: here kilograms descending (note$yfirst), then item name ascending. Since PHP 8.0 all sorts are stable: equal elements keep their order. - PHP 8.4 added
array_find,array_find_key,array_anyandarray_all, and PHP 8.5 addedarray_firstandarray_last. Before them, people wrote small loops or usedreset()andend(), which you will still see in older code.
Arrays as sets and lookup tables, and what they cost
Inside the engine, an array is a hash table: each key is hashed to find its slot, so reading or writing $a[$key] takes about the same time whether the array has ten elements or ten million. (When the keys are exactly 0, 1, 2 … in order, PHP stores a more compact "packed" array, but that is an optimisation you never have to ask for.) Searching for a value, on the other hand, means looking at every element. That difference shapes how experienced PHP developers write lookups.
<?php
declare(strict_types=1);
$visitors = ["ana", "bo", "ana", "chen", "bo", "ana", "dev"];
// Distinct values, two ways.
echo implode(",", array_keys(array_unique($visitors))), " => ", implode(",", array_unique($visitors)), "\n";
$seen = [];
foreach ($visitors as $v) {
$seen[$v] = true;
}
echo implode(",", array_keys($seen)), "\n";
// Counting occurrences.
print_r(array_count_values($visitors));
// Membership: isset on a key is a hash lookup; in_array scans every element.
$banned = array_flip(["mallory", "trudy"]);
foreach (["bo", "trudy"] as $name) {
echo $name, isset($banned[$name]) ? " is banned" : " may enter", "\n";
}
// Set operations on values.
$monday = ["ana", "bo", "chen"];
$tuesday = ["bo", "dev", "chen"];
echo "both days: ", implode(",", array_intersect($monday, $tuesday)), "\n";
echo "only Monday: ", implode(",", array_diff($monday, $tuesday)), "\n";
echo "either day: ", implode(",", array_unique([...$monday, ...$tuesday])), "\n";
// Index rows by id once, then look them up directly.
$users = [["id" => 7, "name" => "Ana"], ["id" => 3, "name" => "Bo"], ["id" => 12, "name" => "Chen"]];
$byId = array_column($users, null, "id");
echo "user 3 is ", $byId[3]["name"], "; ids: ", implode(",", array_keys($byId)), "\n";0,1,3,6 => ana,bo,chen,dev
ana,bo,chen,dev
Array
(
[ana] => 3
[bo] => 2
[chen] => 1
[dev] => 1
)
bo may enter
trudy is banned
both days: bo,chen
only Monday: ana
either day: ana,bo,chen,dev
user 3 is Bo; ids: 7,3,12The patterns to take away:
- A set is an array whose keys are the members.
$seen[$v] = trueadds a member,isset($seen[$v])tests membership in constant time on average, andarray_keys($seen)lists the members.array_flipturns a list of values into exactly such a lookup table. Checking a few thousand names against a ban list within_arrayinside a loop does millions of comparisons; withisseton flipped keys it does a few thousand lookups. This one change fixes a surprising number of slow PHP pages. array_uniquekeeps the first occurrence with its original key, so its result can have gaps (here keys 0, 1, 3, 6). Wrap it inarray_valuesif you need a list. Note that it compares values as strings by default.array_count_valuescounts how often each value occurs, which is a one-line histogram.array_intersectandarray_diffcompute set intersection and difference of values; their_keyvariants work on keys.array_column($rows, null, "id")re-indexes rows by one of their fields. When you will look rows up by id many times, build this index once instead of searching the list each time.
The price of this flexibility is memory. Every element of a PHP array carries a hash, a key and a value slot, so an array of a million small integers uses many times the memory of the same numbers in a C array. For most web requests that never matters. When it does (large imports, long-running workers), stream the data with generators instead of loading it all, or look at the specialised structures in the SPL (SplFixedArray, SplObjectStorage) and the ds extension.
Three traps worth knowing by heart
<?php
declare(strict_types=1);
// Assigning an array copies it (lazily). Objects are different.
$original = ["red", "green"];
$copy = $original;
$copy[] = "blue";
echo count($original), " vs ", count($copy), "\n";
// To change elements in place, foreach can take a reference...
$prices = [100, 250, 80];
foreach ($prices as &$price) {
$price = (int) round($price * 1.1);
}
unset($price); // ...and you must break the reference afterwards.
echo implode(", ", $prices), "\n";
// Here is what happens if you forget the unset.
$letters = ["a", "b", "c"];
foreach ($letters as &$letter) {
}
foreach ($letters as $letter) {
}
echo implode(", ", $letters), "\n";
// in_array compares loosely unless you ask for strict.
$codes = ["0", "1e1", "abc"];
var_dump(in_array(10, $codes), in_array(10, $codes, true));
// isset is false for a key whose value is null; array_key_exists is not.
$profile = ["name" => "Sione", "phone" => null];
var_dump(isset($profile["phone"]), array_key_exists("phone", $profile));2 vs 3
110, 275, 88
a, b, b
bool(true)
bool(false)
bool(false)
bool(true)Misconception
"After a foreach loop, the loop variable is gone." It is not, and if the loop took it by reference (as &$letter), it is still a reference to the last element. The second loop above then assigns each element in turn to that last slot: first "a", then "b", then the slot's own value "b". The array ends as a, b, b. The rule: after any foreach (… as &$x), write unset($x); immediately, or better, use array_map and avoid references altogether.
Misconception
"in_array tells me whether this exact value is in the array." By default it compares with ==, so the integer 10 "is in" an array containing the string "1e1". Pass true as the third argument for ===. The same goes for array_search and array_keys with a search value. Most codebases' linters insist on the strict flag.
Misconception
"isset($a['k']) checks whether a key exists." It checks that the key exists and its value is not null. For a key that is present with a null value, isset says false and array_key_exists says true. Usually isset (or ??) is what you want for input; use array_key_exists when null is a meaningful stored value.
These three have something in common: in each case PHP did what its rules say, quietly, and the program carried on with a wrong value. Copying is the safe default for arrays, so the first block's result (2 vs 3) is usually what you want: a function or a second variable cannot change your array behind your back. The traps appear only when you opt out of the defaults, with references, or rely on loose comparison without noticing. Static analysers such as PHPStan flag all three patterns, which is one reason professional teams run one on every change.
Strings are bytes
A PHP string is a sequence of bytes. PHP does not know or care what encoding they are in. Today almost all text is UTF-8, where a letter such as ï, ó or é takes two bytes, most Chinese, Japanese and Korean characters three, and an emoji four. So every function that counts, cuts or pads "characters" by bytes is wrong for such text.
<?php
declare(strict_types=1);
$word = "naïve";
echo strlen($word), " bytes, ", preg_match_all('/./u', $word), " characters\n";
echo strtoupper($word), " | ", bin2hex(substr($word, 0, 3)), " | ", bin2hex("ï"), "\n";
// strpos returns the position, or false. Position 0 is falsy!
$path = "admin/settings";
$pos = strpos($path, "admin");
echo $pos ? "found" : "not found", " / ", $pos !== false ? "found" : "not found", "\n";
var_dump(str_contains($path, "set"), str_starts_with($path, "admin"), str_ends_with($path, ".php"));
// Splitting, joining, padding, formatting.
$csv = "Lagos,Kraków,Medellín,Busan";
$parts = explode(",", $csv);
echo implode(" | ", array_map(fn(string $c): string => str_pad($c, 9, "."), $parts)), "\n";
echo sprintf("%05.1f|%-6s|%+d|%x", 3.14159, "ok", 42, 255), "\n";
echo number_format(1234567.891, 2), " / ", number_format(1234567.891, 2, ",", "."), "\n";
// Heredoc interpolates; nowdoc does not. The closing marker's indentation is removed.
$name = "Priya";
$items = ["tea" => 2, "rice" => 1];
$letter = <<<TEXT
Dear {$name},
You ordered {$items['tea']} packets of tea.
TEXT;
echo $letter, "\n";
echo <<<'RAW'
Literal: {$name} stays as written.
RAW;
echo "\n";
// Regular expressions (PCRE): the u flag makes them work on UTF-8 characters.
preg_match('/(\d{4})-(\d{2})-(\d{2})/', "Due 2026-11-19, paid", $m);
echo "year $m[1], month $m[2], day $m[3]\n";
echo preg_replace('/\s+/', " ", "too many\n\tspaces"), "\n";
// JSON round trip. JSON_THROW_ON_ERROR turns bad input into an exception.
$json = json_encode(["city" => "São Paulo", "tags" => ["food", "music"]], JSON_UNESCAPED_UNICODE);
echo $json, "\n";
$data = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
echo $data["tags"][1], "\n";6 bytes, 5 characters
NAïVE | 6e61c3 | c3af
not found / found
bool(true)
bool(true)
bool(false)
Lagos.... | Kraków.. | Medellín | Busan....
003.1|ok |+42|ff
1,234,567.89 / 1.234.567,89
Dear Priya,
You ordered 2 packets of tea.
Literal: {$name} stays as written.
year 2026, month 11, day 19
too many spaces
{"city":"São Paulo","tags":["food","music"]}
musicLook closely at the first lines:
strlen("naïve")is 6, becauseïis the two bytesc3 af. Counting with a Unicode-aware regular expression (/./u) gives the 5 characters a reader sees.strtoupperonly changes the ASCII lettersatoz(since PHP 8.2 it ignores the system locale on purpose), soïstays lower case.substr($word, 0, 3)cut the string after three bytes, in the middle ofï: the result ends in a lonec3, which is not valid UTF-8. We printed it in hexadecimal because printing it raw would put a broken character on screen. Text truncated this way is a real bug in real applications (think of a news site cutting headlines to fit).str_padpadded by bytes too, soKrakówandMedellíncame out shorter than the others on screen.
The fix is the mbstring extension: mb_strlen, mb_substr, mb_strtoupper, mb_str_pad (8.3), mb_trim and mb_ucfirst (8.4) work in characters. It is enabled in most PHP installations, but it is an extension, so check with php -m; the minimal build used to test this course does not include it, which is why the program counts characters with a regular expression. For language-aware work (sorting names in a given language, formatting dates and numbers for a locale), use the intl extension.
The rest of the program is everyday string work:
strposreturns the position orfalse. When the text is found at position 0,if ($pos)treats the 0 as false and says "not found". Always compare with!== false, or use the PHP 8.0 functionsstr_contains,str_starts_withandstr_ends_with, which return plain booleans.explodeandimplodesplit and join on a separator; for real CSV with quoted fields, usestr_getcsvorfgetcsv.sprintfformats:%05.1fis width 5, zero-padded, one decimal;%-6sleft-aligns in 6 columns;%+dalways shows the sign;%xis hexadecimal.number_formatinserts thousands separators, and its last two arguments let you follow the conventions of countries that write1.234.567,89.- Heredoc (three less-than signs and a label, then the text, then the label again) is a multi-line double-quoted string; nowdoc, the same with the first label in single quotes, is a multi-line single-quoted one. Since PHP 7.3 the closing marker may be indented, and that much indentation is removed from every line, so heredocs can sit neatly inside indented code.
preg_matchandpreg_replaceuse Perl-compatible regular expressions. Add theuflag whenever the text may contain non-ASCII characters.json_encodeandjson_decode: passtrueas the second argument ofjson_decodeto get arrays rather thanstdClassobjects, and always useJSON_THROW_ON_ERROR, otherwise invalid JSON silently returnsnull.
Exercises
1. Arrays and strings
Warm-upComputationalWhat does this program print?
<?php
$a = ["1" => "a", 1 => "b", "01" => "c"];
echo count($a), $a[1], "\n";
2. Arrays and strings
CoreComputationalCalled without a callback, array_filter removes falsy values. What does this print?
<?php
$n = array_filter([5, 0, 7, 0, 9]);
echo implode(",", array_keys($n)), "\n";
3. Arrays and strings
CoreComputationalWhat does this program print?
<?php
$a = ["x", "y", "z"];
unset($a[0]);
echo json_encode($a), "\n";
4. Arrays and strings
Warm-upComputationalThe file is saved as UTF-8. What does echo strlen("Kraków"); print?
5. Arrays and strings
CoreComputationalWhat does this program print?
<?php
$n = [10, 20, 30, 40];
foreach ($n as &$v) {
}
foreach ($n as $v) {
}
echo implode(",", $n), "\n";
6. Arrays and strings
CoreComputationalWhat does this program print?
<?php
$w = ["kiwi", "fig", "apple", "date"];
usort($w, fn($a, $b) => [strlen($a), $a] <=> [strlen($b), $b]);
echo implode(" ", $w), "\n";
7. Arrays and strings
StretchComputationalStart from $src = [3 => "a", 5 => "b", 9 => "c"];. Which of these operations leave the original integer keys (3, 5, 9 or a subset of them) in their result? List the letters.
- a:
array_filter($src, fn($x) => $x !== "b") - b:
array_map(fn($x) => strtoupper($x), $src) - c:
sort($src)(then look at$src) - d:
asort($src)(then look at$src) - e:
array_values($src) - f:
array_reverse($src)
Further reading and resources
- PHP Manual: ArraysKeys, conversion rules, destructuring and copy behaviour.
- PHP Manual: Array functionsThe full list, from array_any to usort.
- PHP Manual: StringsQuoting, interpolation, heredoc and nowdoc.
- PHP Manual: Multibyte StringThe mb_* functions for working with characters rather than bytes.
- PHP Manual: PCREpreg_match, preg_replace and the regular-expression syntax PHP uses.