PHP

Extract a Portion or Slice from an Array

Learn to extract a specific segment or 'slice' from a PHP array using a starting offset and length, useful for pagination, partial processing, or sub-array creation.

<?php
$products = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam', 'Microphone', 'Headphones'];
echo "Original Products Array: ";
print_r($products);

// Extract elements from index 2, with a length of 3
$slice1 = array_slice($products, 2, 3);
echo "Slice from index 2, length 3: ";
print_r($slice1);
/* Output:
Original Products Array: Array ( [0] => Laptop [1] => Mouse [2] => Keyboard [3] => Monitor [4] => Webcam [5] => Microphone [6] => Headphones )
Slice from index 2, length 3: Array ( [0] => Keyboard [1] => Monitor [2] => Webcam )
*/

// Extract elements from index 4 to the end of the array
$slice2 = array_slice($products, 4);
echo "Slice from index 4 to end: ";
print_r($slice2);
/* Output:
Slice from index 4 to end: Array ( [0] => Webcam [1] => Microphone [2] => Headphones )
*/

// Extract using a negative offset (from end of array), preserving keys
$slice3 = array_slice($products, -3, 2, true);
echo "Slice last 3 elements (length 2), preserving keys: ";
print_r($slice3);
/* Output:
Slice last 3 elements (length 2), preserving keys: Array ( [4] => Webcam [5] => Microphone )
*/
How it works: This snippet demonstrates `array_slice()`, a highly versatile PHP function for extracting a specific portion or 'slice' from an array. You can specify a starting `offset` (positive for from the beginning, negative for from the end) and an optional `length`. It also has a `preserve_keys` parameter to either re-index the resulting slice numerically or maintain the original keys. This is extremely useful for pagination, processing subsets of data, or dynamically generating partial lists from a larger array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs