← Back to Chapters

PHP array_slice() Function

? PHP array_slice() Function

? Quick Overview

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.

? Key Concepts

  • Works on indexed and associative arrays
  • Supports negative indexes
  • Can preserve original keys

? Live Sandbox: Visualize the Slice

Adjust the sliders to see how the parameters affect the result.

 
PHP Equivalent: array_slice($fruits, 1, 2);

⚡ Syntax / Theory

? View Code Example
// Syntax of array_slice function
array_slice($array, $start, $length, $preserve_keys);

?️ Code Example 1: Basic Usage

? View Code Example
// Extract elements starting from index 2
<?php
$fruits = array("Apple","Banana","Cherry","Date","Elderberry");
$sliced = array_slice($fruits,2);
print_r($sliced);
?>

? Live Output / Explanation

Output will start from Cherry and continue till the end. Indexes are re-numbered automatically.

?️ Code Example 2: Specifying Length

? View Code Example
// Extract 3 elements starting from index 1
<?php
$fruits = array("Apple","Banana","Cherry","Date","Elderberry");
$sliced = array_slice($fruits,1,3);
print_r($sliced);
?>

?️ Code Example 3: Preserving Keys

? View Code Example
// 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);
?>

? Interactive Example (JS Simulation)

? View Code Example
// JavaScript simulation of array slicing
const fruits=["Apple","Banana","Cherry","Date","Elderberry"];
const result=fruits.slice(2,4);
console.log(result);

? Use Cases

  • Pagination systems
  • Extracting recent records
  • Processing sub-arrays

✅ Tips & Best Practices

  • Use negative index to slice from the end
  • Enable key preservation for associative arrays
  • Safe to use without modifying original data

? Try It Yourself

  • Slice the last two elements of an array
  • Preserve keys in a multidimensional array
  • Experiment with negative lengths