Hàm mảng_splice() trong PHP
Ví dụ
Xóa các phần tử khỏi mảng và thay thế nó bằng các phần tử mới:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Hãy tự mình thử »Định nghĩa và cách sử dụng
Hàm array_splice() loại bỏ các phần tử đã chọn khỏi một mảng và thay thế nó bằng các phần tử mới. Hàm này cũng trả về một mảng có các phần tử đã bị loại bỏ.
Mẹo: Nếu hàm không loại bỏ bất kỳ phần tử nào (độ dài=0), mảng được thay thế sẽ được chèn từ vị trí của tham số bắt đầu (Xem Ví dụ 2).
Lưu ý: Các khóa trong mảng được thay thế không được giữ nguyên.
Cú pháp
array_splice( array, start, length, array )
Giá trị tham số
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start
removing elements.
0 = the first element.
If this value is set to a negative number, the function will start that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies how many elements will
be removed, and also length of the returned array.
If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will
remove all elements, starting from the position set by the start-parameter.
|
array | Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array. |
Chi tiết kỹ thuật
Giá trị trả về: | Trả về mảng bao gồm các phần tử được trích xuất |
---|---|
Phiên bản PHP: | 4+ |
Thêm ví dụ
ví dụ 1
Ví dụ tương tự như ví dụ ở đầu trang, nhưng đầu ra là mảng trả về:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>
Hãy tự mình thử »Ví dụ 2
Với tham số độ dài được đặt thành 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
Hãy tự mình thử »❮ Tham chiếu mảng PHP