PHP array_slice() Function

PHP array_slice() Function is used to extract a slice of the array. PHP array_slice() function is PHP built-in function.

Syntax :

array_slice(array $array , int $start , int|null $length = null , bool $preserve_keys = false);

Parameter,

$array : Required. It is input array.

$start : Required. It is numeric position value in array which specifies where the function will start the slice.
           If $start=0, It will start at the first element of array.
           If $start <0, The function will start slicing that start position value from the end of the array.
           If $start >0, It will start at that start position value in the array.

$length : Optional. It is numeric value which specifies the length of the returned array.
             If $length <0, The function will stop slicing that start position value from the end of the array.
             If $length >0, It will stop slicing at that length position value in the array.
             If this value is not set, the function will return all elements which is starting from the position set by the start parameter.

$preserve_keys : Optional. It specifies that keys are preserved or not. Default value is false.
                          If It is true, keys are preserved.
                          If It is false, keys are not preserved.

Return : The array_slice() returns sliced array as specified by the start and length parameters.

Let's see below example to understand php array_slice() Function in details.
           

 

Example :

<?php
$array = array("sap","html","css","java","mysql","bootstrap","asp","oracle","php");
echo "<br><br>Look at sliced array which start at 2nd position and stop after 3 elements where preserve_keys is false<br>";
$sliced_array = array_slice($array,2,3); // preserve_keys is false.
print_r($sliced_array);

echo "<br><br>Look at sliced array which start at 1st position and stop after 2 elements where preserve_keys is true. <br>";
$sliced_array = array_slice($array,1,2,true); // preserve_keys is true.
print_r($sliced_array);
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

56191