array_slice
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
Extracts a slice of an array.
C C23
C23
#include <stdio.h>
int main(void) {
int xs[] = {1, 2, 3, 4, 5};
int out[3];
for (int i = 0; i < 3; i++) { // offset 1, length 3
out[i] = xs[1 + i];
}
printf("[");
for (int i = 0; i < 3; i++) {
printf(i ? ", %d" : "%d", out[i]);
}
printf("]\n");
return 0;
}
Output
[2, 3, 4]
C++ C++26
C++26
#include <iostream>
#include <vector>
int main() {
std::vector<int> xs = {1, 2, 3, 4, 5};
// iterator range [begin+1, begin+4): offset 1, length 3
std::vector<int> part(xs.begin() + 1, xs.begin() + 4);
std::cout << "[";
for (size_t i = 0; i < part.size(); ++i) {
if (i) std::cout << ", ";
std::cout << part[i];
}
std::cout << "]\n";
return 0;
}
Output
[2, 3, 4]
C# v11.0.100
v11.0.100
var xs = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine($"[{string.Join(", ", xs.GetRange(1, 3))}]");
Output
[2, 3, 4]
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
fmt.Println([]int{1, 2, 3, 4, 5}[1:4])
}
Output
[2 3 4]
Java v27.0.1
v27.0.1
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(Arrays.copyOfRange(new int[]{1, 2, 3, 4, 5}, 1, 4)));
}
}
Output
[2, 3, 4]
JavaScript v26.13.1
v26.13.1
console.log([1, 2, 3, 4, 5].slice(1, 4))
Output
[ 2, 3, 4 ]
PHP v8.6.0
v8.6.0
echo json_encode(array_slice([1, 2, 3, 4, 5], 1, 3));
Output
[2,3,4]
Python v3.15.2
v3.15.2
print([1, 2, 3, 4, 5][1:4])
Output
[2, 3, 4]
Rust v1.99.1
v1.99.1
fn main() {
println!("{:?}", &[1, 2, 3, 4, 5][1..4]);
}
Output
[2, 3, 4]
TypeScript v26.13.1
v26.13.1
const xs: number[] = [1, 2, 3, 4, 5];
console.log(xs.slice(1, 4));
Output
[ 2, 3, 4 ]
Language differences
C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops, covering a positive offset and length — negative arguments are not implemented.
C++: slices with the iterator-range constructor.
Go: uses slice syntax [start:end].
Java: uses Arrays.copyOfRange(arr, from, to).
JavaScript: uses slice(start, end).
PHP: array_slice takes the length as its third argument.
Python: uses slice syntax [start:end].
Rust: uses slice syntax [start:end].