Skip to content

Step 1 of 5 · Reading · ~4 min

Learn

Arrays

Arrays — One Type, Two Roles

Most languages ship a list type and a dictionary type. PHP ships one: array. It is an ordered map — a sequence of key/value pairs that remembers the order you inserted them. A "list" is simply an array whose keys happen to be 0, 1, 2, ....

<?php
$weights = [1.75, 12.5, 0.4];                 // keys 0, 1, 2
$depot   = ["Lisbon" => 12, "Porto" => 5];    // string keys

Both are the same type. array() is the older spelling of []; you will meet it in old code and the two are identical.

Building and reading

<?php
$weights = [1.75, 12.5, 0.4];
$weights[] = 3.0;                 // append using the next integer key
echo count($weights), "\n";
echo $weights[0], "\n";

$depot = ["Lisbon" => 12, "Porto" => 5];
$depot["Faro"] = 1;               // add or overwrite by key
print_r($depot);

//> 4
//> 1.75
//> Array
//> (
//>     [Lisbon] => 12
//>     [Porto] => 5
//>     [Faro] => 1
//> )

The bracket-with-nothing-inside form is the standard append. print_r() is the readable dump; var_dump() is the one that also shows types.

What happens when the key is missing?

PHP complains — a notice on 7.4, a warning on PHP 8 — and hands you null. Ask before you reach:

What you needUse
A default value$depot["Madrid"] ?? 0
A yes-or-no answerisset($depot["Madrid"])
Is the key present even if it holds null?array_key_exists("Madrid", $depot)

unset leaves a hole

Removing an element does not renumber the ones after it. This is the array behaviour that surprises people most.

<?php
$ids = [101, 102, 103];
unset($ids[1]);
print_r($ids);
print_r(array_values($ids));

//> Array
//> (
//>     [0] => 101
//>     [2] => 103
//> )
//> Array
//> (
//>     [0] => 101
//>     [1] => 103
//> )

array_values() throws the keys away and renumbers from zero. One more detail worth carrying: the next auto-index is one past the highest integer key that has ever existed, so appending to the array above produces key 3, not 2.

Keys get cast

Only int and string can be keys. Anything else is converted first, which means two keys you thought were different can silently collide.

You writeKey actually stored
$a["8"]8 — a numeric string becomes an int
$a[8.7]8 — floats are truncated
$a[true]1
$a[null]""

Iterating

<?php
$depot = ["Lisbon" => 12, "Porto" => 5, "Faro" => 1];
foreach ($depot as $city => $count) {
    echo "$city: $count\n";
}

//> Lisbon: 12
//> Porto: 5
//> Faro: 1

Insertion order, always — for numeric and string keys alike. Nothing is sorted unless you sort it.

The toolbox

FunctionDoes
count($a)how many elements
in_array($v, $a)is this value present (returns a bool)
array_search($v, $a)the key of the first match, or false
array_keys($a) / array_values($a)just the keys / just the values
array_merge($a, $b)join two arrays
array_sum($a)total of the numbers
min($a) / max($a)smallest / largest — one array argument is fine
sort($a) / rsort($a)sort in place, ascending / descending
<?php
$nums = [3, 8, 2, 9, 1];
echo max($nums), " ", min($nums), " ", array_sum($nums), "\n";
echo max([-3, -1, -7]), "\n";

//> 9 1 23
//> -1

Your exercise

Largest Number reads one line of space-separated integers and prints the biggest one.

The starter's line array_map('intval', explode(' ', $line)) splits the text on spaces and converts each piece to an int. (array_map gets a lesson of its own next; here it just hands you $nums ready to use.) max() accepts a whole array, so the answer is a single line.

The mistake the grader catches is rolling your own loop seeded with $max = 0. The hidden test feeds -3 -1 -7 and expects -1, and a zero seed prints 0 because zero beats every negative value in the list. If you do write the loop, seed it with the first element instead. Print just the number, then a newline.

Up nextarray_map, array_filter, array_reduceArrays

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…