• Post category:PHP

What is array_slice Function in PHP

Array slice in PHP

The array slice function in PHP is used to allow slice an array into smaller parts with the array_slice() function, which accepts three arguments: the origianl array, index position (offset) at which tostart slicing, and the number of elements to return from the starting offset.

Ex:

<?php
$rainbow = array('violet', 'indigo', 'blue', 'yellow', 'green', 'red','orange');
// extract 3 central values and output : ('blue', 'yellow', 'green')
$arr = array_slice($rainbow, 2, 3);
print_r($arr);
?>

Output:

 array slice in PHP
To extract a segment from the end of an array ( rather than the beginning), passarray_slice() a negative offset.

Ex:

<?php
$rainbow = array('violet', 'indigo', 'blue', 'yellow', 'green', 'red','orange');
// extract 3 central values starting from the end and output: (' green', 'red','orange')
$arr = array_slice($rainbow, -4, 3);
print_r($arr);
?>

Output:

 array slice in PHP

Leave a Reply