06/04/2021, 14:46
Hàm array_splice() trong PHP - PHP Function
$lenght dương: Code $input = range(0,10); array_splice($input, 5, 4, ["25","22"]); echo "<pre>"; print_r($input); echo "</pre>"; Kết quả Array ( [0] => 0 [1] => 1 [2] => 2 ...
Hàm array_splice() xóa phần tử trong mảng và thay thế bằng một phần tử hoặc một số phần tử khác.
Cú pháp
Cú pháp: array_splice($array, $offset [, $lenght, $replace]);
Trong đó:
$arraylà mảng dữ liệu truyền vào.$offsetlà vị trí của phần tử đầu tiên bị xóa.
Các phần tử tron dấu [ ] có thể không truyền vào:
$lenghtlà số phần tử bị xóa.$replacephần tử hoặc mảng thay thế các phần tử bị xóa.
Ví dụ
$lenght dương:
Code
$input = range(0,10); array_splice($input, 5, 4, ["25","22"]); echo "<pre>"; print_r($input); echo "</pre>";
Kết quả
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 25
[6] => 22
[7] => 9
[8] => 10
)$lenght âm:
Code
$input = range(0,10); array_splice($input, 2, -2); echo "<pre>"; print_r($input); echo "</pre>";
Kết quả
Array
(
[0] => 0
[1] => 1
[2] => 9
[3] => 10
)$lenght = 0:
Code
$input = range(0,10); array_splice($input, 5, 0); echo "<pre>"; print_r($input); echo "</pre>";
Kết quả
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
)Tham khảo: php.net
Nguồn: Zaidap.com.net