The array_slice() function extracts a portion of an array without modifying the original array. It is commonly used when working with subsets of data.
Adjust the sliders to see how the parameters affect the result.
array_slice($fruits, 1, 2);
// Syntax of array_slice function
array_slice($array, $start, $length, $preserve_keys);
// Extract elements starting from index 2
<?php
$fruits = array("Apple","Banana","Cherry","Date","Elderberry");
$sliced = array_slice($fruits,2);
print_r($sliced);
?>
Output will start from Cherry and continue till the end. Indexes are re-numbered automatically.
// Extract 3 elements starting from index 1
<?php
$fruits = array("Apple","Banana","Cherry","Date","Elderberry");
$sliced = array_slice($fruits,1,3);
print_r($sliced);
?>
// Preserve original array keys
<?php
$fruits = array("a"=>"Apple","b"=>"Banana","c"=>"Cherry","d"=>"Date","e"=>"Elderberry");
$sliced = array_slice($fruits,2,2,true);
print_r($sliced);
?>
// JavaScript simulation of array slicing
const fruits=["Apple","Banana","Cherry","Date","Elderberry"];
const result=fruits.slice(2,4);
console.log(result);