PHP array_slice() Function: Description, Parameters, Return Value, and Usage Examples
The article explains PHP's array_slice() function, detailing its purpose, parameter meanings, return value, and provides multiple code examples demonstrating how to extract portions of an array with various offset, length, and key‑preservation options.
Function Overview
The array_slice() function returns a portion of an array based on the specified offset and optional length parameters.
Parameters
array : The input array.
offset : If non‑negative, the slice starts at that index; if negative, it starts that many elements from the end of the array.
length (optional): The number of elements to extract. A positive value extracts forward, a negative value stops that many elements from the end, and omitting it extracts to the end of the array.
preserve_keys (optional, default false ): When true , original array keys are retained; otherwise the function reindexes numerically.
Return Value
Returns an array containing the selected slice of the original array.
Examples
<?php
$input = array("a", "b", "c", "d", "e");
// Example 1: Get elements from index 2 to the end
$output = array_slice($input, 2);
// $output contains "c", "d", "e"
// Example 2: Get one element two positions from the end
$output = array_slice($input, -2, 1);
// $output contains "d"
// Example 3: Get the first three elements, preserving original keys
$output = array_slice($input, 0, 3, true);
// $output contains [0 => "a", 1 => "b", 2 => "c"]
// Example 4: Using print_r to display results
print_r(array_slice($input, 2, -1));
// Outputs: Array ( [0] => c )
print_r(array_slice($input, 2, -1, true));
// Outputs: Array ( [2] => c )
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.