array_slice versus array_spliceΒΆ

A: array_slice returns a segment of the input array, which it does not alter. array_splice is used to remove a segment and replace it will something else, or simply to insert or remove a segment. Examples:

<?php
$i6 = $i5 = $i4 = $i3 = $i2 = $i1 = $input;

array_splice($i1, 2, 2); // removes "law" and "math"
print_r($i1);

array_splice($i2, 2);    // leaves "chem", "biology"
print_r($i2);

// Negative values indicate "from (or up to) the end"
// Remove from offset 1 up to (but not including) last element, -1
array_splice($i3, 1, -1); // leaves "chem", "physics"
print_r($i3);

// Remove starting at last element and moving toward front, removing 1 total elements
array_splice($i4, -1, 1); // removes "physics"
print_r($i4);

// To replace a segment
array_splice($i5, 2, 2, array("English", "art")); // replaces "law", "math" with "English", "art"
print_r($i5);

// To insert the segment, use 0 for removal
array_splice($i6, 2, 0, array("English", "art"));
print_r($i6);