PHP - Funktion array_slice()
Beispiel
Beginnen Sie den Slice mit dem dritten Array-Element und geben Sie die restlichen Elemente im Array zurück:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definition und Verwendung
Die Funktion array_slice() gibt ausgewählte Teile eines Arrays zurück.
Hinweis: Wenn das Array Zeichenfolgenschlüssel enthält, behält das zurückgegebene Array die Schlüssel immer bei (siehe Beispiel 4).
Syntax
array_slice(array, start, length, preserve)
Parameterwerte
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
Rückgabewert: | Gibt ausgewählte Teile eines Arrays zurück |
---|---|
PHP-Version: | 4+ |
PHP-Änderungsprotokoll: | Der Preserve -Parameter wurde in PHP 5.0.2 hinzugefügt |
Mehr Beispiele
Beispiel 1
Beginnen Sie den Slice ab dem zweiten Array-Element und geben Sie nur zwei Elemente zurück:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Beispiel 2
Verwendung eines negativen Startparameters:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Beispiel 3
Wenn der Preserve-Parameter auf true gesetzt ist:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Beispiel 4
Sowohl mit String- als auch mit Integer-Schlüsseln:
<?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-Array-Referenz