Hint: Add to existing value using $arr[index] + number [OK]
Common Mistakes:
Printing old value without update
Adding index instead of value
Confusing array indexes
4. Identify the error in the following PHP code snippet:
$arr = [1, 2, 3]; $arr[3] = 4; echo $arr[3];
medium
A. Accessing an undefined index causes an error
B. Cannot echo array elements directly
C. Syntax error in array declaration
D. Assigning to index 3 adds a new element without error
Solution
Step 1: Check array indexes and assignment
Array has indexes 0,1,2 initially. Assigning $arr[3] = 4 adds a new element at index 3.
Step 2: Confirm if this causes error
PHP allows adding new elements by assigning to new indexes without error.
Final Answer:
Assigning to index 3 adds a new element without error -> Option D
Quick Check:
PHP arrays auto-expand on new index assignment [OK]
Hint: Assigning new index adds element; no error in PHP [OK]
Common Mistakes:
Thinking accessing undefined index causes error
Confusing syntax error with runtime behavior
Believing echo can't print array elements
5. Given the array $arr = [2, 4, 6, 8];, which code snippet correctly doubles each element's value by modifying the array in place?
hard
A. for ($i = 0; $i < count($arr); $i++) { $arr[$i] *= 2; }
B. $arr = array_fill(0, count($arr), 2 * $arr[0]);
C. array_map(fn($v) => $v * 2, $arr);
D. foreach ($arr as $value) { $value = $value * 2; }
Solution
Step 1: Understand how to modify array elements in place
Using a for loop with index allows direct modification of each element.
Step 2: Analyze each option
A: foreach copies values, does not modify original array. B: array_fill replaces all elements with same value, incorrect. C: array_map returns new array, original unchanged. D: for loop modifies $arr[$i] directly.
Final Answer:
for ($i = 0; $i < count($arr); $i++) { $arr[$i] *= 2; } -> Option A
Quick Check:
Use indexed loop to modify array elements [OK]
Hint: Use for loop with indexes to change array elements directly [OK]
Common Mistakes:
Modifying foreach loop variable instead of array
Expecting array_map to change original array
Using array_fill incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.