Lesson 2 of 4
Arrays and functions in PHP
Associative arrays, foreach, and the array functions that replace most loops.
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" + 3is 8 (numeric conversion);"5" . 3is "53" (string join).isset($x)is false when $x is null; usearray_key_existsto 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 testedLesson 3: PDO: prepared statements, fetching and transactionsConnect with PDO, bind values so user input can never become SQL, fetch rows the right way, and group writes in a transaction.Next lesson
Take the PHP testApply what you just read; every answer is explained.Test
PHP interview questions for junior developersWhat interviewers ask about PHP fundamentals and web security, answered briefly.Interview
PHP certificateFree with an account; download the PDF.Certificate
More in Programming