Home >>PHP Array Functions >PHP array_slice() Function

PHP array_slice() Function

PHP array_slice() Function

PHP array_slice() function is used to fetch a part of any given array by slicing through it according to the users choice. It accepts up to four parameters $array, $start, $length, $preserve. It returns the selected or the sliced parts of the given array.

Syntax:

array_slice($array, $start, $length, $preserve);

Parameter Values

Parameter Description
Array This is a required parameter. This parameter defines the given array.
start This is a required parameter. This parameter defines where the function will start the slice.
length This is an optional parameter. This parameter defines the length of the returned array.
preserve This is an optional parameter. This parameter defines if the function should preserve or reset the keys.

Here is an example of array_slice() function in PHP:

<html>
<body>
<pre>
<?php
$a=array("A","B","H","I","M","A","N","Y","U");
print_r(array_slice($a,4));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => M
    [1] => A
    [2] => N
    [3] => Y
    [4] => U
)

Example 2:

<html>
<body>
<pre>
<?php
$a=array("A","B","H","I","M","A","N","Y","U");
print_r(array_slice($a,0,4));
echo "<br>";
print_r(array_slice($a,4,5,true));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => A
    [1] => B
    [2] => H
    [3] => I
)

Array
(
    [4] => M
    [5] => A
    [6] => N
    [7] => Y
    [8] => U
)

No Sidebar ads