Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_splice()

Example

Remove elements from an array and substitute them with new elements.

<?php
$a1=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”,“d”=>“yellow”);
$a2=array(“a”=>“purple”,“b”=>“orange”);
array_splice($a1,0,2,$a2);
print_r($a1);
?>

Definition and Usage

The array_splice() function removes specified elements from an array and replaces them with new elements. It also returns an array containing the removed elements.

Tip: If no elements are removed (length=0), the new elements are inserted at the position specified by the start parameter (see Example 2).

 

Note: The keys in the replaced array are not preserved.

Syntax

array_splice(array, start, length, array)

Parameter Values

 

Parameter

Description

array

Required. Specifies the array to modify.

start

Required. Numeric value. Specifies the position where the function will begin removing elements. 0 refers to the first element. If set to a negative number, the function will start that many positions from the end of the array. For example, -2 means start at the second-to-last element.

length

Optional. Numeric value. Specifies how many elements will be removed and determines the length of the returned array. If set to a negative number, the function will stop removing elements that many positions from the end of the array. If this value is not provided, the function will remove all elements starting from the position specified by the start parameter.

array

Optional. Specifies an array of elements to insert into the original array. If only one element is being inserted, it can be a string instead of an array.

Technical Details

Return Value:

Returns an array containing the removed elements.

PHP Version:

4+

More Examples

Example 1

The same example as shown earlier on the page, but with the output being the returned array.

<?php
$a1=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”,“d”=>“yellow”);
$a2=array(“a”=>“purple”,“b”=>“orange”);
print_r(array_splice($a1,0,2,$a2));
?>

Example 2

With the length parameter set to 0:

<?php
$a1=array(“0”=>“red”,“1”=>“green”);
$a2=array(“0”=>“purple”,“1”=>“orange”);
array_splice($a1,1,0,$a2);
print_r($a1);
?>