PHP Function Reference

PHP array_slice() Function



The PHP array_slice() function returns the sequence of elements from the given array as specified by the offset and length parameters. If the array have string keys, the returned array will always preserve the keys.

Syntax

array_slice(array, offset, length, preserve_keys)

Parameters

array Required. Specify the input array.
offset Required. Specify offset parameter which denotes the position in the array, not the key.
  • If it is non-negative, the sequence will start at that offset in the array.
  • If it is negative, the sequence will start that far from the end of the array.
length Optional. Specify the length of the returned array.
  • If length is a positive number, then the sequence will have up to that many elements in it.
  • If the array is shorter than the length, then only the available array elements will be present.
  • If length is a negative number then the sequence will stop slicing that far from the last element.
  • If it is omitted, then the sequence will have everything from offset up until the end of the array.
preserve_keys Optional. This function reorders and resets the integer array indices by default. This behavior can be changed by setting this parameter to true. String keys are always preserved, regardless of this parameter.

Return Value

Returns the slice. If the offset is larger than the size of the array, an empty array is returned.

Exceptions

NA.

Example:

The example below shows the usage of array_slice() function.

<?php
$Arr = array('a', 'b', 'c', 'd', 'e', 'f');

//slicing arrays
$result1 = array_slice($Arr, 2, 3);
$result2 = array_slice($Arr, -2, 3);
//slicing arrays with preserving keys
$result3 = array_slice($Arr, 2, 3, true);

echo "result1:\n";
print_r($result1);
echo "\nresult2:\n";
print_r($result2);
echo "\nresult3:\n";
print_r($result3);
?>

The output of the above code will be:

result1:
Array
(
    [0] => c
    [1] => d
    [2] => e
)

result2:
Array
(
    [0] => e
    [1] => f
)

result3:
Array
(
    [2] => c
    [3] => d
    [4] => e
)

Example:

Consider one more example where array with mixed keys is sliced using array_slice() function.

<?php
$Arr = array('a'=>'red', 
             'b'=>'green', 
             '10'=>'blue', 
             '25'=>'yellow', 
             'e'=>'black', 
             'f'=>'white');

//slicing arrays
$result1 = array_slice($Arr, 0, 4);
$result2 = array_slice($Arr, 0, 4, true);

echo "result1:\n";
print_r($result1);
echo "\nresult2:\n";
print_r($result2);
?>

The output of the above code will be:

result1:
Array
(
    [a] => red
    [b] => green
    [0] => blue
    [1] => yellow
)

result2:
Array
(
    [a] => red
    [b] => green
    [10] => blue
    [25] => yellow
)

❮ PHP Array Reference