PHP array_slice() Functie
Voorbeeld
Start de slice vanaf het derde array-element en retourneer de rest van de elementen in de array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definitie en gebruik
De functie array_slice() retourneert geselecteerde delen van een array.
Opmerking: als de array tekenreekssleutels heeft, behoudt de geretourneerde array altijd de sleutels (zie voorbeeld 4).
Syntaxis
array_slice(array, start, length, preserve)
Parameterwaarden
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:
|
Technische details
Winstwaarde: | Retourneert geselecteerde delen van een array |
---|---|
PHP-versie: | 4+ |
PHP-wijzigingslogboek: | De bewaarparameter is toegevoegd in PHP 5.0.2 |
Meer voorbeelden
voorbeeld 1
Start het segment vanaf het tweede array-element en retourneer slechts twee elementen:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Voorbeeld 2
Een negatieve startparameter gebruiken:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Voorbeeld 3
Met de parameter behouden ingesteld op true:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Voorbeeld 4
Met zowel string- als integer-sleutels:
<?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));
?>
❮ Referentie voor PHP-array