array_splice
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array
Removes and replaces a segment in place: modifies the original array and returns the removed part; complements read-only array_slice. Negative offsets count from the tail; replacement keys are not preserved.
C C23
#include <stdio.h>
#include <string.h>
/* in-place splice over a pointer array: returns the new length */
static int splice(const char *items[], int n, int off, int len,
const char *repl[], int rn, const char *removed[]) {
if (off < 0) off += n;
for (int i = 0; i < len; i++) removed[i] = items[off + i];
memmove(items + off + rn, items + off + len,
(size_t)(n - off - len) * sizeof(items[0]));
for (int i = 0; i < rn; i++) items[off + i] = repl[i];
return n - len + rn;
}
static void show(const char *v[], int n) {
for (int i = 0; i < n; i++) printf(i ? ",%s" : "%s", v[i]);
}
int main(void) {
const char *removed[4];
const char *r2[] = {"orange", "pink"};
const char *items[8] = {"red", "green", "blue", "yellow"};
int n = splice(items, 4, 1, 2, NULL, 0, removed);
show(removed, 2);
printf(" | ");
show(items, n);
printf("\n");
const char *items2[8] = {"red", "green", "blue", "yellow"};
n = splice(items2, 4, 1, 1, r2, 2, removed);
show(removed, 1);
printf(" | ");
show(items2, n);
printf("\n");
const char *items3[8] = {"red", "green", "blue", "yellow"};
n = splice(items3, 4, -1, 1, NULL, 0, removed); // negative offset
show(removed, 1);
printf(" | ");
show(items3, n);
printf("\n");
return 0;
}
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
C++ C++26
#include <iostream>
#include <string>
#include <vector>
/* erase + insert compose the splice; copy the removed range out first */
static std::vector<std::string> splice(std::vector<std::string>& in, int off, int len,
const std::vector<std::string>& repl) {
if (off < 0) off += (int)in.size();
std::vector<std::string> removed(in.begin() + off, in.begin() + off + len);
in.erase(in.begin() + off, in.begin() + off + len);
in.insert(in.begin() + off, repl.begin(), repl.end());
return removed;
}
static void show(const std::vector<std::string>& v) {
for (size_t i = 0; i < v.size(); i++) std::cout << (i ? "," : "") << v[i];
}
int main() {
std::vector<std::string> items = {"red", "green", "blue", "yellow"};
std::vector<std::string> removed = splice(items, 1, 2, {});
show(removed);
std::cout << " | ";
show(items);
std::cout << "\n";
items = {"red", "green", "blue", "yellow"};
removed = splice(items, 1, 1, {"orange", "pink"});
show(removed);
std::cout << " | ";
show(items);
std::cout << "\n";
items = {"red", "green", "blue", "yellow"};
removed = splice(items, -1, 1, {});
show(removed);
std::cout << " | ";
show(items);
std::cout << "\n";
return 0;
}
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
C# v11.0.100
var items = new List<string> { "red", "green", "blue", "yellow" };
var removed = items.GetRange(1, 2);
items.RemoveRange(1, 2);
Console.WriteLine(string.Join(",", removed) + " | " + string.Join(",", items));
items = new List<string> { "red", "green", "blue", "yellow" };
removed = items.GetRange(1, 1);
items.RemoveRange(1, 1);
items.InsertRange(1, new[] { "orange", "pink" });
Console.WriteLine(string.Join(",", removed) + " | " + string.Join(",", items));
items = new List<string> { "red", "green", "blue", "yellow" };
removed = items.GetRange(3, 1);
items.RemoveRange(3, 1);
Console.WriteLine(string.Join(",", removed) + " | " + string.Join(",", items));
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
Go v1.27.4
package main
import (
"fmt"
"strings"
)
// three-part concatenation: [:off] + replacement + [off+len:]
func splice(in []string, off, length int, repl ...string) ([]string, []string) {
if off < 0 {
off += len(in)
}
removed := append([]string(nil), in[off:off+length]...)
out := make([]string, 0, len(in)-length+len(repl))
out = append(out, in[:off]...)
out = append(out, repl...)
out = append(out, in[off+length:]...)
return removed, out
}
func main() {
removed, items := splice([]string{"red", "green", "blue", "yellow"}, 1, 2)
fmt.Printf("%s | %s\n", strings.Join(removed, ","), strings.Join(items, ","))
removed, items = splice([]string{"red", "green", "blue", "yellow"}, 1, 1, "orange", "pink")
fmt.Printf("%s | %s\n", strings.Join(removed, ","), strings.Join(items, ","))
removed, items = splice([]string{"red", "green", "blue", "yellow"}, -1, 1) // negative offset
fmt.Printf("%s | %s\n", strings.Join(removed, ","), strings.Join(items, ","))
}
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
Java v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
// List.subList is a live view: clear() removes the segment in place
static List<String> splice(List<String> in, int off, int len, String... repl) {
List<String> removed = new ArrayList<>(in.subList(off, off + len));
in.subList(off, off + len).clear();
in.addAll(off, Arrays.asList(repl));
return removed;
}
public static void main(String[] args) {
List<String> items = new ArrayList<>(Arrays.asList("red", "green", "blue", "yellow"));
System.out.println(String.join(",", splice(items, 1, 2)) + " | " + String.join(",", items));
items = new ArrayList<>(Arrays.asList("red", "green", "blue", "yellow"));
System.out.println(String.join(",", splice(items, 1, 1, "orange", "pink")) + " | " + String.join(",", items));
items = new ArrayList<>(Arrays.asList("red", "green", "blue", "yellow"));
System.out.println(String.join(",", splice(items, 3, 1)) + " | " + String.join(",", items));
}
}
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
JavaScript v26.13.1
// JS splice is the same family with the same semantics as PHP:
// in-place modification, returns the removed segment, negative offsets allowed
let items = ["red", "green", "blue", "yellow"];
let removed = items.splice(1, 2);
console.log(removed.join(",") + " | " + items.join(","));
items = ["red", "green", "blue", "yellow"];
removed = items.splice(1, 1, "orange", "pink");
console.log(removed.join(",") + " | " + items.join(","));
items = ["red", "green", "blue", "yellow"];
removed = items.splice(-1, 1);
console.log(removed.join(",") + " | " + items.join(","));
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
PHP v8.6.0
// array_splice modifies $items in place and returns the removed segment
$items = ["red", "green", "blue", "yellow"];
$removed = array_splice($items, 1, 2);
echo implode(",", $removed), " | ", implode(",", $items), "\n";
$items = ["red", "green", "blue", "yellow"];
$removed = array_splice($items, 1, 1, ["orange", "pink"]);
echo implode(",", $removed), " | ", implode(",", $items), "\n";
$items = ["red", "green", "blue", "yellow"];
$removed = array_splice($items, -1, 1); // negative offset
echo implode(",", $removed), " | ", implode(",", $items), "\n";
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
Python v3.15.2
# Python has no splice: capture the removed slice first, then slice-assign
items = ["red", "green", "blue", "yellow"]
removed = items[1:3] # slicing only reads; the removed part must be saved first
items[1:3] = [] # slice assignment mutates in place
print(",".join(removed) + " | " + ",".join(items))
items = ["red", "green", "blue", "yellow"]
removed = items[1:2]
items[1:2] = ["orange", "pink"]
print(",".join(removed) + " | " + ",".join(items))
items = ["red", "green", "blue", "yellow"]
removed = items[-1:]
items[-1:] = []
print(",".join(removed) + " | " + ",".join(items))
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
Rust v1.99.1
fn main() {
// Vec::splice replaces a range in place and yields the removed elements
let mut items = vec!["red", "green", "blue", "yellow"];
let removed: Vec<_> = items.splice(1..3, std::iter::empty::<&str>()).collect();
println!("{} | {}", removed.join(","), items.join(","));
let mut items = vec!["red", "green", "blue", "yellow"];
let removed: Vec<_> = items.splice(1..2, ["orange", "pink"]).collect();
println!("{} | {}", removed.join(","), items.join(","));
let mut items = vec!["red", "green", "blue", "yellow"];
let removed: Vec<_> = items.splice(3..4, std::iter::empty::<&str>()).collect();
println!("{} | {}", removed.join(","), items.join(","));
}
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
TypeScript v26.13.1
// Same runtime as JS splice - the closest PHP counterpart in any language
let items: string[] = ["red", "green", "blue", "yellow"];
let removed: string[] = items.splice(1, 2);
console.log(removed.join(",") + " | " + items.join(","));
items = ["red", "green", "blue", "yellow"];
removed = items.splice(1, 1, "orange", "pink");
console.log(removed.join(",") + " | " + items.join(","));
items = ["red", "green", "blue", "yellow"];
removed = items.splice(-1, 1);
console.log(removed.join(",") + " | " + items.join(","));
green,blue | red,yellow green | red,orange,pink,blue,yellow yellow | red,green,blue
Language differences
C: a hand-written splice — copy the removed segment out first, then memmove the tail to close the gap (or make room for a longer replacement), finally copy the replacement in; a pointer array naturally shows "modify in place + return the removed part".
C++: erase + insert compose the splice semantics (copy the range out before mutating).
C#: List<T> in three steps — GetRange (copy out) + RemoveRange + InsertRange; no single function.
Go: no splice in stdlib; the sample builds three concatenated parts — [:off] + replacement + [off+len:], with negative offsets normalized first.
Java: List.subList is a live view — calling clear() on it removes the segment in place, then addAll inserts; the removed part is copied out first.
JavaScript: splice is the same family with the same semantics as PHP array_splice (in-place, returns the removed segment, negative offsets, len=0 pure insert) — a rare same-name same-meaning pair in cross-language comparison.
PHP: array_splice modifies in place and does not preserve numerical keys (re-indexed from 0); keys of $replacement are not preserved either; $length may be omitted (remove to end) or negative (count from the end); complements array_slice (read-only, leaves the original alone) — $length accepts null since 8.0.
Python: there is no splice — the idiom is slicing the removed part out first, then slice-assigning the same range (lst[1:3] = [...]); equivalent semantics but two explicit steps; lst[1:3] = [] deletes.
Rust: Vec::splice(range, repl) is the closest match to PHP — replaces a range in place and lazily yields the removed elements (the example collects them); split_off is the underlying "split into two" primitive.
TypeScript: same runtime as JS splice.