0
0
PhpHow-ToBeginner · 3 min read

How to Slice Array in PHP: Syntax and Examples

In PHP, you can slice an array using the array_slice() function, which extracts a portion of the array starting from a specified offset and length. The syntax is array_slice(array, offset, length, preserve_keys), where offset is the start position and length is how many elements to take.
📐

Syntax

The array_slice() function extracts a part of an array.

  • array: The original array you want to slice.
  • offset: The starting position (0-based index). Use negative to start from the end.
  • length (optional): Number of elements to extract. If omitted, slices till the end.
  • preserve_keys (optional): If true, keeps original keys; otherwise, keys are reindexed.
php
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
💻

Example

This example shows how to slice an array from position 2, taking 3 elements, and how keys behave with and without preserving them.

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

// Slice from index 2, take 3 elements
$slice1 = array_slice($fruits, 2, 3);

// Slice with keys preserved
$slice2 = array_slice($fruits, 2, 3, true);

print_r($slice1);
print_r($slice2);
?>
Output
Array ( [0] => cherry [1] => date [2] => elderberry ) Array ( [2] => cherry [3] => date [4] => elderberry )
⚠️

Common Pitfalls

Common mistakes include:

  • Using a negative offset without understanding it starts counting from the end.
  • Not preserving keys when you need original keys, which can cause issues when keys matter.
  • Omitting length unintentionally, which slices till the end of the array.
php
<?php
// Wrong: expecting keys preserved but not setting preserve_keys
$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
$slice_wrong = array_slice($numbers, 1, 2);

// Right: preserve keys to keep original keys
$slice_right = array_slice($numbers, 1, 2, true);

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

Quick Reference

Remember these tips when slicing arrays in PHP:

  • Offset can be negative to start from the end.
  • Length is optional; if missing, slice goes to the end.
  • Preserve keys is false by default; set to true to keep original keys.

Key Takeaways

Use array_slice() to extract parts of an array by specifying offset and length.
Offset can be negative to count from the array's end.
Set preserve_keys to true if you want to keep original array keys.
If length is omitted, slicing continues to the end of the array.
Be careful with keys when slicing associative arrays to avoid unexpected reindexing.