PHP array_slice() Fungsi
Contoh
Mulai irisan dari elemen array ketiga, dan kembalikan elemen lainnya dalam array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definisi dan Penggunaan
Fungsi array_slice() mengembalikan bagian array yang dipilih.
Catatan: Jika array memiliki kunci string, array yang dikembalikan akan selalu mempertahankan kunci tersebut (Lihat contoh 4).
Sintaksis
array_slice(array, start, length, preserve)
Nilai Parameter
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:
|
Detail Teknis
Nilai Kembali: | Mengembalikan bagian yang dipilih dari array |
---|---|
Versi PHP: | 4+ |
Log Perubahan PHP: | Parameter pelestarian ditambahkan di PHP 5.0.2 |
Lebih Banyak Contoh
Contoh 1
Mulai irisan dari elemen larik kedua, dan kembalikan hanya dua elemen:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Contoh 2
Menggunakan parameter awal negatif:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Contoh 3
Dengan parameter simpan disetel ke true:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Contoh 4
Dengan kunci string dan integer:
<?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));
?>
Referensi Array PHP