December Code

PHP array interview questions, with answers

The PHP array is one data structure doing the work of several: it is a list, a dictionary and an ordered set of pairs at once. Nearly every PHP program leans on it, so interviews check how arrays are copied, how the array functions differ, and which function to reach for when merging, sorting or searching.

The answers below cover copying, merging, the functional helpers, sorting, key checks, destructuring and the spread operator, with code run on PHP 8.5. Then take the free PHP diagnostic — ten questions across every PHP topic in the bank — to see which of these you can explain but not yet predict.

The questions, with answers

  1. 1.Are PHP arrays copied by value or by reference?

    In short: By value: assigning or passing an array gives an independent copy, made lazily with copy-on-write when one side is changed.

    Arrays are value types in PHP. $b = $a makes $b an independent array, so changing $b[0] leaves $a unchanged, and passing an array to a function gives the function its own copy. To avoid wasting memory, PHP uses copy-on-write: both variables share the same data until one of them is modified, and only then is it copied. To let a function modify the caller's array, declare the parameter by reference, as in function addOne(array &$a).

    $a = [1, 2];
    $b = $a;
    $b[0] = 9;
    echo $a[0], $b[0];
    // 19
  2. 2.What is the difference between array_merge and the + operator in PHP?

    In short: + keeps the left array's value for a duplicate key and adds only new keys; array_merge lets later string keys win and renumbers integer keys.

    The union operator, $x + $y, starts with $x and adds the entries of $y whose keys are not already present, for string and integer keys alike, so the left side wins. array_merge($x, $y) treats keys by type: for string keys the later array's value overwrites the earlier one, while integer keys are not compared at all; every integer-keyed value is appended and renumbered from 0. That is why the + result below keeps k at 1 and has one numbered element, while array_merge has k at 2 and both numbered elements. Use + to fill in defaults and array_merge to combine lists.

    $x = ["k" => 1, "a"];
    $y = ["k" => 2, "b"];
    $u = $x + $y;
    $m = array_merge($x, $y);
    echo json_encode($u), "\n";
    echo json_encode($m);
    // {"k":1,"0":"a"}
    // {"k":2,"0":"a","1":"b"}
  3. 3.What do array_map, array_filter and array_reduce do in PHP?

    In short: array_map transforms every element, array_filter keeps the elements a callback accepts, and array_reduce folds an array into one value.

    array_map(callback, $array) returns a new array of the callback's results for each element; with several arrays it walks them in parallel. array_filter($array, callback) keeps the elements for which the callback returns true, and preserves their keys, so the result may have gaps; array_values renumbers it. array_reduce($array, callback, $initial) passes an accumulator through the elements to produce a single value, such as a sum. Note the inconsistent argument order: array_map takes the callback first, array_filter and array_reduce take the array first. Arrow functions keep these calls short.

    $n = [1, 2, 3, 4];
    $ev = array_filter(
        $n, fn($x) => $x % 2 == 0);
    $sq = array_map(
        fn($x) => $x * $x, $ev);
    echo implode(",", $sq);
    // 4,16
  4. 4.How do sort, asort and ksort differ in PHP?

    In short: sort orders values and throws away the keys; asort orders by value but keeps each key with its value; ksort orders by key.

    PHP's sort functions differ in what they order by and whether they keep keys. sort and rsort order the values and reindex the array from 0, which suits lists. asort and arsort order by value but keep each key paired with its value, which suits associative arrays such as scores by name. ksort and krsort order by key. usort, uasort and uksort take a comparison callback, often written with <=>. All of them sort in place and return true, so their result should not be assigned. Since PHP 8.0 the sorts are stable.

    $ages = ["x" => 3, "y" => 1];
    asort($ages);
    echo json_encode($ages), " ";
    ksort($ages);
    echo json_encode($ages);
    // {"y":1,"x":3} {"x":3,"y":1}
  5. 5.How do you check whether a key exists in a PHP array?

    In short: array_key_exists is true whenever the key is present; isset is also false when the stored value is null.

    array_key_exists($key, $array) answers exactly whether the key is present, whatever its value. isset($array[$key]) returns false both for a missing key and for a key whose value is null, as the code shows, but it is a language construct rather than a function, so it is slightly faster and does not warn. Choose array_key_exists when null is a meaningful stored value, and isset or ?? otherwise. To check for a value rather than a key, in_array searches, and passing true as its third argument makes the comparison strict.

    $a = ["k" => null];
    var_dump(isset($a["k"]));
    // bool(false)
    var_dump(array_key_exists(
        "k", $a));
    // bool(true)
  6. 6.How does array destructuring work in PHP?

    In short: [$a, $b] = $array assigns elements to variables by position, and ["key" => $v] = $array by key; elements can be skipped.

    Short list syntax, the modern form of list(), unpacks an array into variables. Positional destructuring takes elements in order, and an empty slot skips one, as the missing middle element below shows. Keyed destructuring names the keys to take, which suits associative arrays such as database rows. It works in foreach too, as in foreach ($rows as ["id" => $id, "name" => $name]), and it can swap two variables without a temporary: [$a, $b] = [$b, $a]. A missing key produces a warning and null.

    [$first, , $third] = [1, 2, 3];
    ["x" => $x] = ["x" => 5];
    echo $first, $third, $x;
    // 135
  7. 7.What does the spread operator ... do with PHP arrays?

    In short: Inside an array literal, ...$arr inserts that array's elements; since PHP 8.1 string keys are kept, with later keys overwriting earlier ones.

    [...$a, 3] builds a new array from $a's elements followed by 3, which replaces many array_merge calls. Integer keys are renumbered, and since PHP 8.1 string keys are unpacked too, with a later value for the same key overwriting an earlier one, so $c["k"] is 2 below. The same ... in a function call spreads an array into separate arguments, and in a function declaration it collects extra arguments into an array, a variadic parameter. Spreading any Traversable, not only arrays, works in all these positions.

    $a = [1, 2];
    $b = [...$a, 3];
    $c = ["k" => 1, ...["k" => 2]];
    echo count($b), $c["k"];
    // 32

How the diagnostic asks it

One question from the PHP bank, exactly as a sitting would show it. The bank has 5 on arrays and 30 across PHP.

Arrays · mediumPHP-009

What does this PHP code print?

$a = [1, 2];
$b = $a;
$b[] = 3;
$o = new ArrayObject([1, 2]);
$p = $o;
$p[] = 3;
echo count($a), count($o);
  1. 133
  2. 223correct
  3. 322
  4. 432

PHP arrays are values: $b = $a gives $b its own copy (made lazily, when $b is first changed), so appending 3 to $b leaves $a with 2 elements. Objects are different: a variable holds a handle to the object, and $p = $o copies the handle, so $p and $o refer to the same ArrayObject and appending through $p changes what $o sees, 3 elements. The output is 23. 33 treats arrays like objects, as in JavaScript or Java. 22 treats objects like arrays. 32 has both wrong. To get an independent object, use clone.

Measure it

Reading answers tells you what’s true. A diagnostic tells you what you get wrong.

10 PHP questions across its topics, easy to hard, about fifteen minutes. You get a readiness figure with the arithmetic shown, the topics you missed named, and a practice set sized for today. Free: 1 diagnostic a month and 15 problems a day. No card.

What the readiness test measures · how the score is computed

By Harshit · updated