Chức năng: Xóa một vài phần tử mảng và thay thế bằng các phần tử khác
Ngôn ngữ: php - Nhóm: array
CÚ PHÁP
array array_splice ( array &$input, int $offset [, int $length [, array $replacement]] );
Hàm xóa đi một vài phần tử của mảng và có thể thay thế vào đó những phần tử mới do người sử dụng định nghĩa ở các đối số:
INPUT: Mảng đưa vào để xữ lý.
OFFSET: Vị trí xác định việc xóa bỏ phần tử.
+ Nếu OFFSET > 0, mảng được xóa từ vị trí bắt đầu,
+ Nếu OFFSET < 0, mảng được xóa từ vị trí cuối.
LENGTH: Số phần tử bị xóa kể từ vị trí.
REPLACEMENT: Mảng được đưa vào để thêm vào mảng INPUT. Mảng INPUT chỉ được xữ lý thêm vào khi mảng REPLACEMENT tồn tại.
Một vài cách xữ lý tương được với việc sử dụng hàm này:
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
array_pop($input);
array_splice($input, -1);
array_shift($input);
array_splice($input, 0, 1);
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
$input[$x] = $y; // for arrays where key equals offset
array_splice($input, $x, 1, $y);
VÍ DỤ
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// "blue", "black", "maroon")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// "blue", "purple", "yellow");
?>