Definition and Usage
- PHP Version
- 4+
The array_slice() function extracts a specified range of elements from an array and returns the result as a new array. The original array is not modified.
This function provides a simple and useful way to extract a specific range of elements from an array.
Basic Example
// Original array
$array = ['a', 'b', 'c', 'd', 'e'];
/*
Use the array_slice() function to extract
three elements starting from index 1
from the original array and return the result
as a new array.
*/
$sliced_array = array_slice($array, 1, 3);
print_r($sliced_array);
/*
Output:
Array
(
[0] => b
[1] => c
[2] => d
)
*/
For strings, the substr() function extracts a specified range of characters from a string and returns the result as a new string.
Syntax
array_slice(
array $array,
int $offset,
?int $length = null,
bool $preserve_keys = false
): array
/* array_slice(
the original array,
the index at which to start extracting elements[,
the number of elements to extract[,
a boolean value indicating whether to preserve the keys]]
);
*/
Parameters
$array |
Required. The original array. |
|---|---|
$offset |
Required. Specifies the zero-based index at which to start extracting elements.
A negative value may be used, in which case the starting position is determined by counting backward from the end of the array. For example, -1 starts from the last element, and -3 starts from the third element from the end. |
$length |
Optional. The number of elements to extract.
|
$preserve_keys |
Optional. Determines whether the keys of the extracted array should be preserved. This parameter is a boolean value, and its default value is false.
|
Warning:
$preserve_keys can be set to true only for indexed arrays. Keys in associative arrays are always preserved, regardless of this parameter.
Return Values
he function returns a new array containing the result of extracting (slicing) a specified range of elements from the original array.
The returned array includes the elements from the selected range of the original array, and the keys may be preserved or reindexed. (This behavior depends on the fourth parameter, $preserve_keys.)
Examples of Parameters and Return Values
print_r(array_slice($indexed_arr, 0)); // Extract all elements
print_r(array_slice($indexed_arr, 2)); // From index 2 ('C') to the end
print_r(array_slice($indexed_arr, 2, 1)); // One element starting from index 2
print_r(array_slice($indexed_arr, -2, 1)); // One element starting from the second-to-last ('D')
print_r(array_slice($indexed_arr, 7)); // Out of range returns an empty array: Array ( )
// Comparison of key preservation
print_r(array_slice($indexed_arr, 2, 2)); // Keys reindexed: [0] => C, [1] => D
print_r(array_slice($indexed_arr, 2, 2, true)); // Keys preserved: [2] => C, [3] => D
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
)
Array
(
[0] => C
[1] => D
[2] => E
)
Array
(
[0] => C
)
Array
(
[0] => D
)
Array
(
)
Array
(
[0] => C
[1] => D
)
Array
(
[2] => C
[3] => D
)
$associative_arr = [
'a' => 'red',
'b' => 'green',
'c' => 'blue',
'd' => 'olive',
'e' => 'brown'
];
print_r(array_slice($associative_arr, 0)); // Array ( [a] => red [b] => green [c] => blue [d] => olive [e] => brown )
print_r(array_slice($associative_arr, 2)); // Array ( [c] => blue [d] => olive [e] => brown )
print_r(array_slice($associative_arr, 2, 1)); // Array ( [c] => blue )
print_r(array_slice($associative_arr, -2, 1)); // Array ( [d] => olive )
print_r(array_slice($associative_arr, 7)); // Array ( )
// Difference in key preservation based on the third parameter
// In associative arrays, keys are always preserved regardless of this parameter.
print_r(array_slice($associative_arr, 2, 2)); // Array ( [c] => blue [d] => olive )
print_r(array_slice($associative_arr, 2, 2, true)); // Array ( [c] => blue [d] => olive )
Practical Examples
The array_slice() function is useful for extracting a portion of an array. Below are several practical use cases for the array_slice() function.
Extracting Elements from the Beginning of an Array up to a Specific Index
// Log data array
$logData = [
'2022-01-01' => 'Log entry 1',
'2022-01-02' => 'Log entry 2',
/* ... */
];
// Extract log data for the most recent 5 days
$recentLogs = array_slice($logData, 0, 5);
// Output the result
print_r($recentLogs);
Extracting Elements Within a Specific Index Range
// Product list array
$products = [
101 => 'Laptop', // Index 0
102 => 'Smartphone', // Index 1 (starting point!)
103 => 'Headphones', // Index 2
104 => 'Tablet', // Index 3
105 => 'Camera', // Index 4
106 => 'Smartwatch', // Index 5
];
// Extract 3 elements starting from the second element (index 1)
// Set $preserve_keys to true to preserve the original keys (102, 103, 104).
$selectedProducts = array_slice($products, 1, 3, true);
// Output the result
print_r($selectedProducts);
/*
Output:
Array
(
[102] => Smartphone
[103] => Headphones
[104] => Tablet
)
*/
Extracting a Specific Number of Elements from the End of an Array
// Recent activity list array
$recentActivity = [
'Commented on a post',
'Liked a photo',
'Posted a status',
'Followed a user',
'Shared a link',
];
// Extract the most recent 3 activities
$selectedActivity = array_slice($recentActivity, -3, null, true);
// Output the result
print_r($selectedActivity);
References
See also
- PHP array_push() Function – Add Elements to the End of an Array
- PHP array_shift() Function – Remove the First Element from an Array
- PHP array_unshift() Function – Add Elements to the Start of an Array
- PHP array_pop() Function – Remove the Last Element from an Array
- PHP array_search() Function – Searching for a Value in an Array
- PHP array_key_exists() Function – Check if a Key Exists in an Array
- PHP array_keys() Function – Get a List of Array Keys
- PHP array_values() Function – Get a List of Array Values