← Back to all snippets
PHP

Extracting Array Slices in PHP

Efficiently extract sub-arrays from existing PHP arrays without modifying the original. This snippet demonstrates array_slice() to get a portion of an array using offset and length, useful for pagination or data partitioning.

<?php
$numbers = [10, 20, 30, 40, 50, 60, 70];

// Get elements from index 2 with a length of 3
$slice1 = array_slice($numbers, 2, 3);
// Result: [30, 40, 50]

// Get elements from index 4 to the end
$slice2 = array_slice($numbers, 4);
// Result: [50, 60, 70]

// Get last 3 elements using a negative offset
$slice3 = array_slice($numbers, -3);
// Result: [50, 60, 70]

// Get 2 elements starting from 3rd to last element
$slice4 = array_slice($numbers, -5, 2);
// Result: [30, 40]

// Preserve keys (useful for associative arrays)
$colors = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow'];
$sliceWithKeys = array_slice($colors, 1, 2, true);
// Result: ['b' => 'green', 'c' => 'blue'] (keys preserved)

$sliceWithoutKeys = array_slice($colors, 1, 2, false);
// Result: [0 => 'green', 1 => 'blue'] (keys re-indexed)
?>
How it works: The `array_slice()` function in PHP provides a versatile way to extract a portion of an array. It takes an array, an offset (starting position), and an optional length. Negative offsets count from the end of the array. The fourth optional parameter, `preserve_keys`, determines whether original string keys or numeric indices are maintained (if `true`) or if numeric keys are re-indexed from `0` (if `false` or omitted), which is particularly useful for associative arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs