English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_splice() function usage and example

PHP Array Function Manual

The PHP array_splice() function removes a part of an array and replaces it with other values

Syntax

array_splice ( $input, $offset [,$length [,$replacement]] );

Definition and usage

This function frominputelements fromoffsetandlengthspecified elements, andreplacementArray elements (if provided) replace them. It returns an array containing the extracted elements.

Note that the numeric keys in input are not retained.

Parameter

NumberParameters and descriptions
1

input(required)

It specifies an array

2

offset

It specifies where the function will start deleting elements. 0=first element.

3

length(optional)

It specifies the number of elements to delete and the length of the returned array.

4

replacement(optional)

It specifies an array that contains the elements to be inserted into the original array.

Return value

 Returns an array containing the removed elements.

Online example

Using array_splice to modify an array

<?php
   $input = array("red", "black", "pink", "white");
   array_splice($input, 2);
   print_r($input);
   print_r("<br />)
   $input = array("red", "black", "pink", "white");
   array_splice($input, 1, -1);
   print_r($input);
   print_r("<br />)
   $input = array("red", "black", "pink", "white");
   array_splice($input, 1, count($input), "orange");
   print_r($input);
   print_r("<br />)
   $input = array("red", "black", "pink", "white");
   array_splice($input, -1, 1, array("black", "maroon"));
   print_r($input);
   print_r("<br />)
   $input = array("red", "black", "pink", "white");
   array_splice($input, 3, 0, "purple");
   print_r($input);
   print_r("<br />)
?>
Test and see‹/›

Output result:

Array ( [0]=>red [1] =>black )
Array ( [0]=>red [1] =>white )
Array ( [0]=>red [1] =>orange )
Array ( [0]=>red [1] =>black [2pink [3] =>black [4maroon )
Array ( [0]=>red [1] =>black [2pink [3purple [4white )

PHP Array Function Manual