Função PHP array_slice()
Exemplo
Inicie a fatia a partir do terceiro elemento da matriz e retorne o restante dos elementos da matriz:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definição e uso
A função array_slice() retorna partes selecionadas de um array.
Nota: Se o array tiver chaves de string, o array retornado sempre preservará as chaves (veja o exemplo 4).
Sintaxe
array_slice(array, start, length, preserve)
Valores de parâmetro
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:
|
Detalhes técnicos
Valor de retorno: | Retorna partes selecionadas de um array |
---|---|
Versão do PHP: | 4+ |
Registro de alterações do PHP: | O parâmetro preserve foi adicionado no PHP 5.0.2 |
Mais exemplos
Exemplo 1
Inicie a fatia a partir do segundo elemento da matriz e retorne apenas dois elementos:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Exemplo 2
Usando um parâmetro de início negativo:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Exemplo 3
Com o parâmetro preserve definido como true:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Exemplo 4
Com as chaves de string e de número inteiro:
<?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));
?>
❮ Referência de array PHP