PHP

Extract a Portion of an Array (Slicing)

Discover how to extract a specific segment or 'slice' from a PHP array using array_slice, useful for pagination, limiting data display, or getting subsets.

<?php

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Get elements from index 2 (value 3) for a length of 4
$slice1 = array_slice($numbers, 2, 4);
print_r($slice1);

// Get elements from index 5 (value 6) to the end
$slice2 = array_slice($numbers, 5);
print_r($slice2);

// Get the last 3 elements (using negative offset)
$slice3 = array_slice($numbers, -3);
print_r($slice3);

// Expected Output:
// Array
// (
//     [0] => 3
//     [1] => 4
//     [2] => 5
//     [3] => 6
// )
// Array
// (
//     [0] => 6
//     [1] => 7
//     [2] => 8
//     [3] => 9
//     [4] => 10
// )
// Array
// (
//     [0] => 8
//     [1] => 9
//     [2] => 10
// )

?>
How it works: The `array_slice()` function extracts a sequence of elements from an array. It takes the input array, a starting offset (can be positive for start from beginning, or negative for start from end), and an optional length. If length is omitted, it extracts to the end of the array. This is highly effective for pagination, displaying limited results, or processing subsets of data without modifying the original array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs