CodeBlanks Logo Icon CodeBlanks

Slicing with array_slice()

PHP course · Beginner · Lesson 62/116

Learn to take a portion of an array with array_slice().

Slicing with array_slice()

array_slice() takes a portion of an array. It has two main parameters: offset (where to start) and length (how many elements to take).

For example, array_slice([10, 20, 30, 40, 50], 1, 2) starts at index 1 and takes 2 elements; the result is [20, 30]. The original array is not changed; a new array is returned. A negative offset counts from the end: -1 gives the last element.

Negative offset and length

In array_slice(), both offset and length can be negative. A negative offset counts from the end: -2 starts at the second-to-last element. A negative length leaves that many elements off the end.

For example, array_slice([1, 2, 3, 4, 5], -2) returns [4, 5]; array_slice([1, 2, 3, 4, 5], 0, -1) drops the last element and returns [1, 2, 3, 4]. If length is omitted, it goes to the end.

Exercise Take the first three and print them

Define $nums = [10, 20, 30, 40, 50, 60]. Assign the first three elements to $first with array_slice($nums, 0, 3). Then loop with foreach ($first as $n) and print each element with echo $n . "\n".

Show example solution
First take with $first = array_slice($nums, 0, 3);. Then loop with foreach ($first as $n) { echo $n . "\n"; } and print.
Example solution:
<?php
$nums = [10, 20, 30, 40, 50, 60];
// Take the first three and print them
$first = array_slice($nums, 0, 3);
foreach ($first as $n) {
    echo $n . "\n";
}

Test yourself

  1. What is the output of the code below?

    $arr = [1, 2, 3, 4, 5];
    print_r(array_slice($arr, 2, 2));
    • [1, 2]
    • [2, 3]
    • [3, 4]
    • [1, 2, 3]
    Show answer

    [3, 4] — Correct. Starting at index 2 (the 3) and taking 2 elements; the result is [3, 4].

  2. Complete the call to take the last two

    $arr = [1, 2, 3, 4, 5];
    $slice = array_slice($arr, ____);
    print_r($slice);
    Show answer
    $arr = [1, 2, 3, 4, 5];
    $slice = array_slice($arr, -2);
    print_r($slice);
  3. Match each parameter to its behavior

    offset = 1
    Starts at index 1
    length = 2
    Takes 2 elements
    offset = -1
    Starts at last element

All lessons in Beginner