PHP array_slice() Function

PHP array_slice() Function

The array_slice() function in PHP is used to extract a slice of the array. It returns the sequence of elements from the array as specified by the offset and length parameters.

Syntax

array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]]
)

Parameter

array(required)- This array represents the input array.

offset(required)-This parameter signifies the starting position of the array from where the slicing needs to be performed. The various offset values are as follows:

  • If it is greater than 0, the sequence will start at that offset in the array.
  • If offset is negative, the sequence will start from the end of the array.

length(optional)- This parameter refers to the range or limit point upto which the slicing is needed to be done.

  • If length is positive, the sequence will have up to that many elements in it.
  • If the array < (shorter)length, only the available array elements will be present.
  • If length is negative, the sequence will stop that many elements from the end of the array.

preserve_keys (optional)- This parameter represents the function whether to preserve the keys or reset it. If it is set to true, the keys will be preserved else for false (default value) Boolean value resets the keys.

Return

This function returns the slice. If the specified offset is larger than the size of the array, an empty array is returned.

Example 1




Output

Input Array: 
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Sliced Array: 
Array
(
    [0] => c
    [1] => d
    [2] => e
) 

Example 2




Output

 Input Array: 
 Array
 (
     [0] => a
     [1] => b
     [2] => c
     [3] => d
     [4] => e
 )
 Sliced Array: 
 Array
 (
     [0] => d
 ) 

Example 3




Output

Input Array: 
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Sliced Array: 
Array
(
    [2] => c
    [3] => d
)