Jump to: navigation, search

Php array splice

From w3cyberlearnings

Contents

PHP function array_splice

This function removes or inserts element of the array and replaces it with new elements. It returns array with the removed elements.

Syntax array_splice

  • array: array input
  • start: start position for removing or replacing. (Negative number makes the replace starts from the last array element)
  • length (optional): Specifies how many elements will be removed. Negative number makes the length count from the last array element.
  • array (optional): array to be inserted or replaced.
array_splice(array, start, length, array);

Example 1: Insert element

  • When the length is 0, it is for insert.
<?php

$records = array(
	 'Alyssa',
	 'Emma',
	 'Landon',
	 'Alex',
	 'Christ',
	 'Sam',
	 'Mark');

$insert = array('Paul', 'Paula');

array_splice($records, 2, 0, $insert);

print_r($records);
?>

Output

  • Insert Paul and Paula
Array
(
    [0] => Alyssa
    [1] => Emma
    [2] => Paul
    [3] => Paula
    [4] => Landon
    [5] => Alex
    [6] => Christ
    [7] => Sam
    [8] => Mark
)

Example 2: Replace

  • Replace Landon with Paul, Alex with Paula
<?php

$records = array(
	 'Alyssa',
	 'Emma',
	 'Landon',
	 'Alex',
	 'Christ',
	 'Sam',
	 'Mark');

$insert = array('Paul', 'Paula');

array_splice($records, 2, 2, $insert);

print_r($records);
?>

Output

Array
(
    [0] => Alyssa
    [1] => Emma
    [2] => Paul
    [3] => Paula
    [4] => Christ
    [5] => Sam
    [6] => Mark
)

Example 3: Get the remove elements

  • The same as in example 2, however this time we assign the remove elements to $r.
<?php

$records = array(
	 'Alyssa',
	 'Emma',
	 'Landon',
	 'Alex',
	 'Christ',
	 'Sam',
	 'Mark');

$insert = array('Paul', 'Paula');

$r = array_splice($records, 2, 2, $insert);

print_r($r);
?>


Output

Array
(
    [0] => Landon
    [1] => Alex
)

Example 4

<?php

$records = array(
	 'Alyssa',
	 'Emma',
	 'Landon',
	 'Alex',
	 'Christ',
	 'Sam',
	 'Mark');

$insert = array('Paul', 'Paula');

$r = array_splice($records, -2, 0, $insert);
// $r returns nothing

print_r($records);
?>

Output

Array
(
    [0] => Alyssa
    [1] => Emma
    [2] => Landon
    [3] => Alex
    [4] => Christ
    [5] => Paul
    [6] => Paula
    [7] => Sam
    [8] => Mark
)

Example 5:

<?php

$records = array(
	 'Alyssa',
	 'Emma',
	 'Landon',
	 'Alex',
	 'Christ',
	 'Sam',
	 'Mark');

$insert = array('Paul', 'Paula');

$r = array_splice($records, 0, -2, $insert);

print_r($records);
print_r($r);
?>

Output

Array
(
    [0] => Paul
    [1] => Paula
    [2] => Sam
    [3] => Mark
)

Array
(
    [0] => Alyssa
    [1] => Emma
    [2] => Landon
    [3] => Alex
    [4] => Christ
)

Related Links


Navigation
Web
SQL
MISC
References