PHP array_splice()ฟังก์ชัน
ตัวอย่าง
ลบองค์ประกอบออกจากอาร์เรย์และแทนที่ด้วยองค์ประกอบใหม่:
<?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);
?>
ความหมายและการใช้งาน
ฟังก์ชัน array_splice() จะลบองค์ประกอบที่เลือกออกจากอาร์เรย์และแทนที่ด้วยองค์ประกอบใหม่ ฟังก์ชันนี้ยังส่งคืนอาร์เรย์ที่มีองค์ประกอบที่ถูกลบออกด้วย
เคล็ดลับ:หากฟังก์ชันไม่ลบองค์ประกอบใดๆ (ความยาว=0) อาร์เรย์ที่แทนที่จะถูกแทรกจากตำแหน่งของพารามิเตอร์เริ่มต้น (ดูตัวอย่างที่ 2)
หมายเหตุ:คีย์ในอาร์เรย์ที่ถูกแทนที่จะไม่ถูกเก็บรักษาไว้
ไวยากรณ์
array_splice(array, start, length, array)
ค่าพารามิเตอร์
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. |
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับอาร์เรย์ที่ประกอบด้วยองค์ประกอบที่แยกออกมา |
---|---|
รุ่น PHP: | 4+ |
ตัวอย่างเพิ่มเติม
ตัวอย่าง 1
ตัวอย่างเดียวกับตัวอย่างที่ด้านบนของหน้า แต่ผลลัพธ์คืออาร์เรย์ที่ส่งคืน:
<?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));
?>
ตัวอย่าง 2
โดยตั้งค่าพารามิเตอร์ความยาวเป็น 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ การอ้างอิงอาร์เรย์ PHP