Consider the following PHP code snippet:
$arr = [1, 2, 3, 4]; $arr[2] = $arr[0] + $arr[1]; echo $arr[2];
What will be printed?
$arr = [1, 2, 3, 4]; $arr[2] = $arr[0] + $arr[1]; echo $arr[2];
Remember that array indices start at 0 and you can assign new values to existing keys.
The original value at index 2 is 3, but it is replaced by the sum of values at indices 0 and 1, which are 1 and 2. So, 1 + 2 = 3, but since the original value was 3, the new value is 3. However, the code actually sums 1 + 2 = 3, so the output is 3.
Look at this PHP code:
$arr = ["a" => [1, 2], "b" => [3, 4]]; $arr["a"][1] = 5; echo $arr["a"][1];
What will it print?
$arr = ["a" => [1, 2], "b" => [3, 4]]; $arr["a"][1] = 5; echo $arr["a"][1];
Think about how to access and change values inside nested arrays.
The code changes the second element (index 1) of the array under key "a" from 2 to 5. So echo prints 5.
What error does this PHP code produce?
$arr = [10, 20, 30]; $arr[3] += 5; echo $arr[3];
$arr = [10, 20, 30]; $arr[3] += 5; echo $arr[3];
Think about what happens when you try to add to an array element that does not exist yet.
Accessing $arr[3] before it is set triggers a notice about undefined offset. Then PHP treats it as 0 and adds 5, so echo prints 5, but the notice is shown.
Which of the following PHP code snippets will cause a syntax error?
Look carefully at the assignment operators and their usage.
Option C has an incomplete assignment operator '+=' without a value, causing a syntax error.
Given this PHP code:
$arr = []; $arr[2] = 'a'; $arr[] = 'b'; $arr[5] = 'c'; $arr[] = 'd';
How many elements does $arr have after these lines run?
$arr = []; $arr[2] = 'a'; $arr[] = 'b'; $arr[5] = 'c'; $arr[] = 'd';
Remember how PHP assigns keys when using empty brackets and how explicit keys affect the array.
After the first assignment, $arr has key 2. Then $arr[] adds 'b' at the next highest integer key, which is 3. Then key 5 is set to 'c'. Then $arr[] adds 'd' at key 6. So keys are 2,3,5,6 → 4 elements total.