Lesson 52 of 100
Arrays15 min5 checksPHP 8.5

Slice and Splice Arrays

Learn how array_slice() copies a range while array_splice() removes and replaces a range in place, and build a function that reports both outcomes.

01 · THE IDEAREAD → TRY → LEARN

Two tools, two jobs

PHP offers two functions for working with a range of elements, and they are easy to confuse. array_slice() reads: it returns a piece of an array and leaves the original untouched. array_splice() edits: it takes the array by reference, removes a range from it, optionally puts new elements in that spot, and returns the elements it removed.

The key question to ask is: do I want a copy of a range, or do I want to change the array?

Reading a range with array_slice()

The call array_slice($items, 1, 2) means "start at offset 1 and give me two elements." Nothing about $items changes.

Example
<?php
$items = ["red", "green", "blue", "yellow"];
$slice = array_slice($items, 1, 2);
echo json_encode(['slice' => $slice, 'items' => $items], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
{"slice":["green","blue"],"items":["red","green","blue","yellow"]}

The slice holds green and blue, and the original still has all four colours.

Editing a range with array_splice()

The signature is array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []). Pay attention to two things: the first argument is modified directly, and the return value is the list of removed elements, not the new array.

Example
<?php
$items = ["red", "green", "blue", "yellow"];
$removed = array_splice($items, 1, 2, ["orange"]);
echo json_encode(['removed' => $removed, 'items' => $items], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
{"removed":["green","blue"],"items":["red","orange","yellow"]}

Two elements left, one arrived, so the array shrank from four items to three. The function handed back the two it took out.

How offset and length behave

  • A positive offset counts from the start; a negative one counts from the end.
  • If length is omitted or null, everything from offset to the end is removed.
  • A positive length removes that many elements.
  • A negative length stops the removal that many elements before the end.
  • A length of 0 removes nothing, so the replacement is simply inserted at offset.
  • An offset larger than the array is treated as the end, so the replacement is appended.

When you want to replace everything to the end and also supply a replacement, pass count($input) as the length, because a null length with a replacement is easy to misread.

Keys are renumbered

Numeric keys are not preserved by array_splice(). String keys survive, but integer keys in the remaining array are renumbered from zero, and the returned removed list is also a fresh list.

Example
<?php
$data = ['a' => 1, 5 => 2, 9 => 3];
$removed = array_splice($data, 1, 1);
echo json_encode(['removed' => $removed, 'data' => $data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
{"removed":[2],"data":{"a":1,"0":3}}

The key 9 became 0. If your keys carry meaning, do not rely on splicing; use unset() or build a new array instead.

Replacement is cast to an array

A non-array replacement is converted with (array). A plain string becomes a one-element list, but null becomes an empty list, which removes without inserting, and an object is turned into its properties. When the thing you insert might be an array, an object or null, wrap it yourself: [$value].

Working on a copy

Because PHP passes arrays by value to your own functions, a function that accepts array $items and calls array_splice($items, ...) edits only its local copy. That makes it safe to return both pieces of information at once: what was removed and what the array looks like now.

Exercise contract

Write replaceRange(array $items, int $offset, int $length, array $replacement): array. It must not change the caller's array. It returns an associative array with two keys:

  • removed: the elements taken out of the range.
  • result: the list after the range was replaced by $replacement.

For example, replaceRange(["a", "b", "c", "d"], 1, 2, ["x"]) returns removed of ["b", "c"] and result of ["a", "x", "d"]. The tests cover insertion, a negative offset, an offset past the end and a negative length, so rely on the built-in rules instead of hand-writing index math.

Recap

  • array_slice() copies a range and leaves the source alone.
  • array_splice() changes the array in place and returns what it removed.
  • Negative offsets and lengths count from the end.
  • Numeric keys are renumbered, and replacements are cast to arrays.
Before you start

Functions · Arrays · Types

You’ll practice
  • Distinguish extracted data from in-place replacement
  • Implement and test a deterministic PHP 8.4 function
Your task

Make replaceRange() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.