PHP array_slice()ฟังก์ชั่น
ตัวอย่าง
เริ่มสไลซ์จากองค์ประกอบอาร์เรย์ที่สาม และส่งคืนองค์ประกอบที่เหลือในอาร์เรย์:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
ความหมายและการใช้งาน
ฟังก์ชัน array_slice() จะคืนค่าส่วนที่เลือกของอาร์เรย์
หมายเหตุ:หากอาร์เรย์มีคีย์สตริง อาร์เรย์ที่ส่งคืนจะเก็บคีย์ไว้เสมอ (ดูตัวอย่างที่ 4)
ไวยากรณ์
array_slice(array, start, length, preserve)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start the slice.
0 = the first element.
If this value is set to a negative number, the function will start slicing that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies the length of the returned array.
If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
|
preserve | Optional. Specifies if the function should preserve or reset the keys. Possible values:
|
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับส่วนที่เลือกของอาร์เรย์ |
---|---|
รุ่น PHP: | 4+ |
บันทึกการเปลี่ยนแปลง PHP: | เพิ่มพารามิเตอร์ การรักษาไว้ใน PHP 5.0.2 |
ตัวอย่างเพิ่มเติม
ตัวอย่าง 1
เริ่มสไลซ์จากอิลิเมนต์อาร์เรย์ที่สอง และส่งกลับเพียงสองอิลิเมนต์:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
ตัวอย่าง 2
การใช้พารามิเตอร์เริ่มต้นเชิงลบ:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
ตัวอย่างที่ 3
เมื่อตั้งค่าพารามิเตอร์คงไว้เป็น true:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
ตัวอย่างที่ 4
ด้วยคีย์สตริงและจำนวนเต็ม:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown");
print_r(array_slice($a,1,2));
$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown");
print_r(array_slice($a,1,2));
?>
❮ การอ้างอิงอาร์เรย์ PHP