Challenge - 5 Problems
Array Slice and Splice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP array_slice example?
Consider the following PHP code. What will be the output when it runs?
PHP
<?php $array = [10, 20, 30, 40, 50]; $result = array_slice($array, 2, 2); print_r($result); ?>
Attempts:
2 left
💡 Hint
array_slice reindexes keys by default unless you specify the fourth parameter as true.
✗ Incorrect
array_slice returns a portion of the array starting at index 2 (third element) and takes 2 elements. By default, keys are reindexed starting at 0.
❓ Predict Output
intermediate2:00remaining
What does this PHP array_splice code output?
Look at this PHP code snippet. What will be printed?
PHP
<?php $array = [1, 2, 3, 4, 5]; $removed = array_splice($array, 1, 3, [9, 8]); print_r($array); print_r($removed); ?>
Attempts:
2 left
💡 Hint
array_splice removes elements and replaces them with new ones, returning the removed elements.
✗ Incorrect
array_splice removes 3 elements starting at index 1 (2,3,4) and inserts [9,8] in their place. The original array is modified, and the removed elements are returned.
🔧 Debug
advanced2:00remaining
What error does this PHP code raise?
Examine this PHP snippet. What error will it produce when run?
PHP
<?php $array = [5, 10, 15]; $result = array_slice($array, -1, -1); print_r($result); ?>
Attempts:
2 left
💡 Hint
Check the meaning of negative length in array_slice.
✗ Incorrect
array_slice does not accept a negative length parameter. It triggers a warning and returns an empty array.
❓ Predict Output
advanced2:00remaining
What is the output of this PHP array_splice with no length parameter?
What will this PHP code print?
PHP
<?php $array = [100, 200, 300, 400]; $removed = array_splice($array, 2); print_r($array); print_r($removed); ?>
Attempts:
2 left
💡 Hint
If length is omitted, array_splice removes all elements from offset to end.
✗ Incorrect
array_splice removes all elements from index 2 to the end and returns them. The original array is shortened accordingly.
🧠 Conceptual
expert2:00remaining
How many elements remain in the array after this PHP array_splice operation?
Given this PHP code, how many elements will remain in $array after the operation?
PHP
<?php $array = [7, 14, 21, 28, 35, 42]; array_splice($array, 2, 2, [99, 100, 101]); ?>
Attempts:
2 left
💡 Hint
Count how many elements are removed and how many are inserted.
✗ Incorrect
array_splice removes 2 elements starting at index 2 and inserts 3 new elements. So total elements = original 6 - 2 + 3 = 7.