HomebaseWorks
Lesson 2 of 4

Arrays and functions in PHP

Associative arrays, foreach, and the array functions that replace most loops.

EWritten by the HomebaseWorks editorial team · reviewed 26 Oct 2026

PHP arrays are both lists and maps, which confuses people coming from other languages and is the source of several standard interview questions.

Advertisement

Two kinds in one

$list = ['typing', 'excel'];           // keys 0, 1
$map  = ['typing' => 42, 'excel' => 80]; // string keys
$map['sql'] = 70;                        // add
foreach ($map as $skill => $score) {
    echo "$skill: $score\n";
}

Functions that replace loops

$doubled = array_map(fn($n) => $n * 2, [1, 2, 3]);      // [2, 4, 6]
$passed  = array_filter($map, fn($s) => $s >= 50);      // keeps typing? no: 42 < 50
$total   = array_sum($map);
$keys    = array_keys($map);
sort($list);                                            // in place
usort($rows, fn($a, $b) => $a['score'] <=> $b['score']); // by field

The spaceship operator <=> returns -1, 0 or 1 and is the standard way to sort by a field.

Writing a function

function netWpm(int $gross, int $errors, float $minutes = 1.0): float
{
    return max(0, $gross - $errors / $minutes);
}

Type declarations on parameters and return values catch mistakes early and read well in a code review. declare(strict_types=1); at the top of the file makes them strict.

Common questions

  • "5" + 3 is 8 (numeric conversion); "5" . 3 is "53" (string join).
  • isset($x) is false when $x is null; use array_key_exists to test a key that may hold null.
  • == converts types, === does not. Compare with === unless you have a reason not to.
Advertisement
Continue with PHP4 lessons · 2 interview sets · 1 test · 1 certificate
Not tested

More in Programming