How to use array_slice()

In this lesson we look at how we can extract part of an array using array_slice().

The format for the array_slice() function is:

array_slice(array, offset, length)

Suppose we have an array of letters as follows:

<?php
   $letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

Line 1: this is our opening PHP code block declaration.
Line 2: we have an array called $letters which contains the letters a to g.

Now suppose we wish to ignore the first 3 values in the array and return the remaining values.

<?php
   $letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
   
   $output = array_slice($letters, 3);

The value 3 is called the offset. In this case it literally means begin slicing the array at the 4th value (the one at position 3 in the array). Remember, array values start at the 0 position.

Position 0Position 1Position 2Position 3Position 4...etc
abcde...etc

The $output array in this case will be a subset of the array containing the letters d, e, f, and g.

If we wanted to return the 4th, and 5th letters then we can specify another argument in our array_slice() function. The third argument is the length i.e. how many values we wish to return. In this case we are returning 2 values.

<?php
   $letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
   
   $output = array_slice($letters, 3, 2);

In this case the returned letters would be d and e.

What if we don't know the length of the array and want to return the last 3 values of the array?

Well, we can use a negative offset. Imagine that we go backwards from position 0. We know there is nothing actually at position -1. However, we actually say that the last value is in position -1 and the next is position -2 etc.

In our previous example this would mean that letter g is in position -1 and letter f is in position -2.

We can now do the following:

<?php
   $letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
   
   $output = array_slice($letters, -3, 3);

Line 4: We slice the array starting at position -3 and return 3 values.

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

User Avatar

Is it possible to take multiple slices?

by Kerry, 21-Dec-2015

User Avatar

Yes, you can repeat the process as many times as you wish.

Just start with the original array and declare a new array for each slice you require. E.g.

$letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

$slice1 = array_slice($letters, 1, 3);

$slice2 = array_slice($letters, -3, 2);

You could also be quite fancy and use counters or loops but there are probably more elegant ways of achieving the result you require depending on your actual needs.

by Patrick Morrow, 21-Dec-2015

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.