Sling Academy
Home/PHP/PHP Array Slicing: A Practical Guide

PHP Array Slicing: A Practical Guide

Last updated: January 10, 2024

Overview

Array slicing in PHP allows developers to extract a subset of an array. This fundamental technique enables efficient data management and manipulation, critical for any PHP-powered application. This guide introduces PHP array slicing, demonstrating basic to advanced concepts with clear examples.

Introduction to Array Slicing

In PHP, slicing an array means copying a portion of the array into a new array. The original array remains unchanged, while the new array contains only the elements that were “sliced” out. The array_slice() function is used for this purpose:

$originalArray = ["a", "b", "c", "d", "e"];
$slicedArray = array_slice($originalArray, 1, 2);
print_r($slicedArray);

Output:

Array
(
    [0] => b
    [1] => c
)

This code snippet slices the array starting at index 1 and includes the next 2 elements.

Basic Array Slicing With array_slice()

If you want to slice an array from a certain position until the end, you can omit the length parameter:

$array = ["apple", "banana", "cherry", "date", "elderberry"];
$slicedToEnd = array_slice($array, 2);
print_r($slicedToEnd);

Output:

Array
(
    [0] => cherry
    [1] => date
    [2] => elderberry
)

Here, the function slices everything from the third element (index 2) onward.

Selective Array Slicing

You can also create slices with non-sequential keys. It’s possible to do this with a combination of array_slice() and array_keys():

$assocArray = [
    "first" => "apple",
    "second" => "banana",
    "third" => "cherry",
    "fourth" => "date",
    "fifth" => "elderberry"
];
$keysToSlice = ["second", "fourth"];
$selectedSlices = array_intersect_key($assocArray, array_flip($keysToSlice));
print_r($selectedSlices);

Output:

Array
(
    [second] => banana
    [fourth] => date
)

This approach selectively slices elements with the respective keys.

Using Negative Indices

PHP’s array_slice() supports negative indices for the start and length parameters, counting from the end of the array:

$array = ["pencil", "eraser", "sharpener", "ruler", "compass"];
$sliceNegativeIndices = array_slice($array, -3, 2);
print_r($sliceNegativeIndices);

Output:

Array
(
    [0] => sharpener
    [1] => ruler
)

Here, the slice begins at the third element from the end of the array and takes two elements.

Preserving Keys

By default, array_slice() reindexes the sliced elements unless you set the optional preserve_keys parameter to true:

$assocArray = [
    10 => "ten",
    20 => "twenty",
    30 => "thirty",
    40 => "forty",
    50 => "fifty"
];
$preservedSlice = array_slice($assocArray, 1, 3, true);
print_r($preservedSlice);

Output:

Array
(
    [20] => twenty
    [30] => thirty
    [40] => forty
)

The keys are preserved, maintaining their original associations.

Advanced Slicing Patterns

More sophisticated slicing can be achieved by combining array_slice() with functions like array_filter() and array_values(). You can filter an array by some criteria, slice it thereafter, and then re-index it:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = array_filter($array, function($value) {return $value % 2 === 0;});
$evenNumbersSliced = array_slice($evenNumbers, 1, 3);
$evenNumbersReIndexed = array_values($evenNumbersSliced);
print_r($evenNumbersReIndexed);

Output:

Array
(
    [0] => 4
    [1] => 6
    [2] => 8
)

Filtering evens, slicing, and reindexing demonstrates a more advanced use of array slicing.

Conclusion

This guide has traversed the path from the simple use of array_slice() to more sophisticated examples embedding additional PHP array functions. Grasping the potential of PHP array slicing empowers developers to wield arrays with precision and efficiency, reinforcing the foundation of robust PHP application design.

Next Article: Ways to Calculate the Sum of an Array in PHP (7 examples)

Previous Article: How to Update an Element in an Array in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array