PHP array_slice() Funzione
Esempio
Inizia la fetta dal terzo elemento dell'array e restituisce il resto degli elementi nell'array:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definizione e utilizzo
La funzione array_slice() restituisce parti selezionate di un array.
Nota: se l'array ha chiavi di tipo stringa, l'array restituito conserverà sempre le chiavi (vedere l'esempio 4).
Sintassi
array_slice(array, start, length, preserve)
Valori dei parametri
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:
|
Dettagli tecnici
Valore di ritorno: | Restituisce parti selezionate di un array |
---|---|
Versione PHP: | 4+ |
Registro delle modifiche PHP: | Il parametro preservare è stato aggiunto in PHP 5.0.2 |
Altri esempi
Esempio 1
Inizia la fetta dal secondo elemento dell'array e restituisci solo due elementi:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Esempio 2
Utilizzando un parametro di avvio negativo:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Esempio 3
Con il parametro preserve impostato su true:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Esempio 4
Con chiavi di stringa e intere:
<?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));
?>
❮ Riferimento all'array PHP