Función PHP array_slice()
Ejemplo
Comience el segmento desde el tercer elemento de la matriz y devuelva el resto de los elementos de la matriz:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Definición y uso
La función array_slice() devuelve partes seleccionadas de una matriz.
Nota: si la matriz tiene claves de cadena, la matriz devuelta siempre conservará las claves (consulte el ejemplo 4).
Sintaxis
array_slice(array, start, length, preserve)
Valores paramétricos
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:
|
Detalles técnicos
Valor devuelto: | Devuelve las partes seleccionadas de una matriz |
---|---|
Versión PHP: | 4+ |
Registro de cambios de PHP: | El parámetro de preservación se agregó en PHP 5.0.2 |
Más ejemplos
Ejemplo 1
Comience el segmento desde el segundo elemento de la matriz y devuelva solo dos elementos:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
Ejemplo 2
Usando un parámetro de inicio negativo:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
Ejemplo 3
Con el parámetro preserve establecido en verdadero:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
Ejemplo 4
Con claves de cadena y enteras:
<?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));
?>
❮ Referencia de matriz de PHP