0
0
PHPprogramming~5 mins

Array slice and splice in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the array_slice() function do in PHP?
It returns a portion of an array without modifying the original array. You specify the start position and length of the slice.
Click to reveal answer
beginner
How does array_splice() differ from array_slice()?
array_splice() removes a portion of an array and can replace it with new elements. It modifies the original array.
Click to reveal answer
intermediate
What happens if you use a negative start index in array_slice()?
The slice starts that many elements from the end of the array. For example, -2 means start from the second last element.
Click to reveal answer
intermediate
What does array_splice($array, 2, 3, ['a', 'b']) do?
It removes 3 elements from $array starting at index 2, then inserts 'a' and 'b' at that position, modifying $array.
Click to reveal answer
intermediate
Does array_slice() preserve keys by default?
No, by default it reindexes the returned array starting from 0. You can preserve keys by passing true as the fourth argument.
Click to reveal answer
Which function modifies the original array in PHP?
Aarray_map()
Barray_slice()
Carray_merge()
Darray_splice()
What does array_slice($arr, 1, 2) return?
ATwo elements starting from index 1
BElements from index 1 to 2 inclusive
CAll elements except the first
DThe entire array
How do you preserve keys when using array_slice()?
APass true as the fourth argument
BPass false as the third argument
CUse array_splice() instead
DKeys are always preserved
What does array_splice($arr, 0, 0, ['x']) do?
ARemoves the first element
BInserts 'x' at the start without removing elements
CReplaces the first element with 'x'
DReturns an empty array
If you want to get the last 3 elements of an array without changing it, which is best?
Aarray_splice($arr, -3)
Barray_shift() three times
Carray_slice($arr, -3)
Darray_pop() three times
Explain the difference between array_slice() and array_splice() in PHP.
Think about whether the original array changes or not.
You got /4 concepts.
    Describe how to use array_splice() to remove elements and insert new ones.
    Remember it works like cutting out and pasting in new pieces.
    You got /4 concepts.