Función PHP array_splice()
Ejemplo
Elimina elementos de una matriz y reemplázalos con elementos nuevos:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Definición y uso
La función array_splice() elimina los elementos seleccionados de una matriz y los reemplaza con elementos nuevos. La función también devuelve una matriz con los elementos eliminados.
Sugerencia: si la función no elimina ningún elemento (longitud = 0), la matriz reemplazada se insertará desde la posición del parámetro de inicio (consulte el ejemplo 2).
Nota: Las claves de la matriz reemplazada no se conservan.
Sintaxis
array_splice(array, start, length, array)
Valores paramétricos
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start
removing elements.
0 = the first element.
If this value is set to a negative number, the function will start that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies how many elements will
be removed, and also length of the returned array.
If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will
remove all elements, starting from the position set by the start-parameter.
|
array | Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array. |
Detalles técnicos
Valor devuelto: | Devuelve la matriz que consta de los elementos extraídos. |
---|---|
Versión PHP: | 4+ |
Más ejemplos
Ejemplo 1
El mismo ejemplo que el ejemplo en la parte superior de la página, pero la salida es la matriz devuelta:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>
Ejemplo 2
Con el parámetro de longitud establecido en 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ Referencia de matriz de PHP