← Back to Chapters

PHP array_splice() Function

? PHP array_splice() Function

? Quick Overview

The array_splice() function in PHP is used to remove a portion of an array and optionally replace it with another array. It is useful when you need to modify an array by removing, replacing, or inserting elements at a specific position.

? Key Concepts

  • Works directly on the original array
  • Can remove, replace, or insert elements
  • Supports negative indexes
  • Very useful for mid-array modifications

⚡ Syntax / Theory

? View Code Example
// General syntax of array_splice in PHP
array_splice($array,$start,$length,$replacement);

?️ Code Example 1: Basic Removal

? View Code Example
// Remove two elements starting from index 2

? Output Explanation

The elements Cherry and Date are removed, leaving Apple, Banana, and Elderberry.

?️ Code Example 2: Replacement

? View Code Example
// Replace two elements with new values

? Output Explanation

Cherry and Date are replaced by Grapes and Kiwi at the same position.

?️ Code Example 3: Negative Index

? View Code Example
// Remove second last element using negative index

?️ Code Example 4: Insert Without Deleting

? View Code Example
// Insert elements without removing any existing items

? Live Interactive Playground

Current Array: ["Red", "Green", "Blue", "Yellow", "Purple"]

Resulting Array:

 

? Interactive Concept (Visual Idea)

Imagine an array as a row of boxes. array_splice() cuts boxes from a chosen position and optionally inserts new boxes at the same location — all in one operation.

? Use Cases

  • Insert items into the middle of arrays
  • Replace outdated data dynamically
  • Remove unwanted array segments
  • Manage ordered lists like menus or steps

✅ Tips & Best Practices

  • Use array_splice() when you need multiple changes at once
  • Always remember it modifies the original array
  • Negative indexes simplify end-based operations
  • Use length 0 for pure insertion

? Try It Yourself

  • Create a city array and replace middle values
  • Insert elements without deleting existing ones
  • Remove items from the end using negative indexes
  • Combine removal and insertion in one call