0
0
PHPprogramming~10 mins

Array slice and splice in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get a slice of the array from index 1 to 3.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry', 'date', 'fig'];
$slice = array_slice($fruits, [1], 3);
print_r($slice);
?>
Drag options to blanks, or click blank then click option'
A1
B0
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as the start index which includes the first element.
Using 3 which starts slicing too late.
2fill in blank
medium

Complete the code to remove 2 elements from the array starting at index 2 using array_splice.

PHP
<?php
$colors = ['red', 'green', 'blue', 'yellow', 'purple'];
array_splice($colors, [1], 2);
print_r($colors);
?>
Drag options to blanks, or click blank then click option'
A0
B1
C3
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 which removes elements starting too early.
Using 3 which removes elements starting too late.
3fill in blank
hard

Fix the error in the code to correctly insert 'orange' at index 1 without removing elements.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
array_splice($fruits, [1], 0, 'orange');
print_r($fruits);
?>
Drag options to blanks, or click blank then click option'
A0
B2
C1
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 inserts before 'apple'.
Using 2 inserts after 'banana'.
4fill in blank
hard

Fill both blanks to create a slice of the array from index 2 to the end.

PHP
<?php
$numbers = [10, 20, 30, 40, 50];
$slice = array_slice($numbers, [1], [2]);
print_r($slice);
?>
Drag options to blanks, or click blank then click option'
A2
B3
Cnull
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as start index returns the first three elements.
Using 0 as length returns an empty array.
5fill in blank
hard

Fill all three blanks to remove 1 element at index 1 and insert 'kiwi' and 'mango' instead.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, [1], [2], [[3]]);
print_r($fruits);
?>
Drag options to blanks, or click blank then click option'
A1
B2
C'kiwi', 'mango'
Attempts:
3 left
💡 Hint
Common Mistakes
Removing 2 elements removes too many items.
Not passing the inserted fruits as an array.