Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

How to slice an array in PHP

Zubair Idris Aweda

Overview

Slicing an array means printing some elements of an array for a specified range using their index positions.

To slice an array in PHP, use the array_slice() in-built PHP array function.

Parameters

This function takes in the array to be sliced, and an offset (the index to start from). It can take other parameters like the number of elements to return (like a delimiter). The function has a definition:

array_slice(
    array $array, // Array to be sliced
    int $offset, // Slice starting point
    ?int $length = null, // Number of elements to take
): array

Return value

The function always returns an array from the original array.

Code

  1. To slice and array, start from the fourth element.
<?

// Create array of numbers
$numbers = [1, 23, 4, 12, 45, 5, 56];

// Get numbers from index 3 till the end
$sliced = array_slice($numbers, 3);

// Output the new array
print_r($sliced); // Returns [12, 45, 5, 56]

Explanation

In this example, the array is sliced, starting from the fourth element (index 3). It takes this element and all the elements after it and forms a new array that is returned.

Code

  1. To slice an array, start from the third element, take only 4 elements.
<?php

// Create array of letters
$letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

/**
Slice the array to 4 letters,
starting from the letter at index 3.
**/
$sliced = array_slice($letters, 3, 4);

// Output resulting array
print_r($sliced); // Returns ['d', 'e', 'f', 'g']

Explanation

In this example, four elements are taken out of the $letters array. These elements are taken in the order we arranged. It starts from the fourth element (‘d’) and stops once four elements are taken.

RELATED TAGS

php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring