0
0
PhpHow-ToBeginner · 3 min read

How to Use array_slice in PHP: Syntax and Examples

Use array_slice in PHP to extract a portion of an array by specifying the start index and length. It returns a new array without modifying the original. The syntax is array_slice(array, offset, length, preserve_keys).
📐

Syntax

The array_slice function extracts a slice of an array starting from a specified offset. It has four parameters:

  • array: The input array to slice.
  • offset: The starting index (0-based). Use negative values to start from the end.
  • length (optional): Number of elements to extract. If omitted, slices to the end.
  • preserve_keys (optional): Boolean to keep original keys (default is false).
php
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
💻

Example

This example shows how to extract a part of an array starting from index 1, taking 3 elements, and how to preserve keys.

php
<?php
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Extract 3 elements starting from index 1
$slice = array_slice($fruits, 1, 3);

// Extract 3 elements starting from index 1, preserving keys
$slice_preserved = array_slice($fruits, 1, 3, true);

print_r($slice);
print_r($slice_preserved);
?>
Output
Array ( [0] => banana [1] => cherry [2] => date ) Array ( [1] => banana [2] => cherry [3] => date )
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting that array_slice does not modify the original array but returns a new one.
  • Not understanding that keys are reindexed by default, which can cause issues if keys matter.
  • Using a negative offset or length incorrectly.

Example of wrong and right usage:

php
<?php
$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];

// Wrong: expecting keys to be preserved by default
$slice_wrong = array_slice($numbers, 1);

// Right: preserve keys explicitly
$slice_right = array_slice($numbers, 1, null, true);

print_r($slice_wrong);
print_r($slice_right);
?>
Output
Array ( [0] => twenty [1] => thirty ) Array ( [20] => twenty [30] => thirty )
📊

Quick Reference

ParameterDescriptionDefault
arrayInput array to sliceRequired
offsetStart index (0-based), negative counts from endRequired
lengthNumber of elements to extractnull (to end)
preserve_keysKeep original keys if truefalse

Key Takeaways

array_slice returns a new array slice without changing the original array.
By default, keys are reindexed; use preserve_keys=true to keep original keys.
Offset can be negative to start counting from the end of the array.
If length is omitted, array_slice extracts until the end of the array.
Always check if you need to preserve keys to avoid unexpected results.