array_splice

(PHP 4, PHP 5, PHP 7, PHP 8)

array_spliceElimina y reemplaza una porción de array

Descripción

function array_splice(
    array &$array,
    int $offset,
    ?int $length = null,
    mixed $replacement = []
): array

array_splice() elimina los elementos designados por offset y length del array array y los reemplaza por los elementos del array replacement, si este último es proporcionado.

Nota:

Las claves numéricas en array no son preservadas.

Nota:

Si replacement no es un array, se convertirá en uno por conversión (i.e. (array) $replacement). Esto puede producir resultados inesperados al utilizar un objeto o null como argumento replacement.

Parámetros

array

El array de entrada.

offset

Si offset es positivo, el inicio de la sección a eliminar estará en esta posición partiendo del inicio del array array.

Si offset es negativo, el inicio de la sección a eliminar estará en esta posición partiendo del final del array array.

length

Si length es omitido, todos los elementos del array desde la posición offset hasta el final del array serán eliminados.

Si length es proporcionado y positivo, entonces tantos elementos serán eliminados.

Si length es proporcionado y negativo, entonces tantos elementos serán eliminados del final del array.

Si length es proporcionado y vale cero, entonces ningún elemento será eliminado.

Sugerencia

Para eliminar todo desde la posición offset hasta el final del array cuando replacement también es proporcionado, utilizar count($input) para length.

replacement

Si el array replacement es proporcionado, entonces los elementos eliminados son reemplazados por los elementos de este array.

Si el offset y length son tales que nada es eliminado, entonces los elementos del array replacement son insertados en la posición offset.

Nota:

Las claves del array replacement no son preservadas.

Si replacement es solo un elemento no es necesario rodear el elemento con array() o corchetes, a menos que el elemento sea él mismo un array, un objeto o null.

Valores devueltos

Retorna un array conteniendo los elementos extraídos.

Historial de cambios

Versión Descripción
8.0.0 length ahora es nullable.

Ejemplos

Ejemplo #1 Ejemplos con array_splice()

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>

El ejemplo anterior mostrará:

array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "yellow"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "orange"
}
array(5) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(5) "black"
  [4]=>
  string(6) "maroon"
}

Ejemplo #2 Declaraciones equivalentes a ejemplos de array_splice() diversos

Las declaraciones siguientes son equivalentes:

<?php

// añadir dos elementos a $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));

// eliminar el último elemento de $input
array_pop($input);
array_splice($input, -1);

// eliminar el primer elemento de $input
array_shift($input);
array_splice($input, 0, 1);

// insertar dos elementos al inicio de $input
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));

// reemplazar el valor en $input en el índice $x
$input[$x] = $y; // para arrays donde las claves son iguales al offset
array_splice($input, $x, 1, $y);

?>

Véase también

add a note

User Contributed Notes 32 notes

up
36
mrsohailkhan at gmail dot com
14 years ago
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )  
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow ) 
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
up
24
royanee at yahoo dot com
13 years ago
When trying to splice an associative array into another, array_splice is missing two key ingredients:
  - a string key for identifying the offset
  - the ability to preserve keys in the replacement array

This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
        $replacement = (array) $replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
                $offset = $key_indices[$offset];
        }
        if (isset($input[$length]) && is_string($length)) {
                $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
                + $replacement
                + array_slice($input, $offset + $length, NULL, TRUE);
}

$fruit = array(
        'orange' => 'orange',
        'lemon' => 'yellow',
        'lime' => 'green',
        'grape' => 'purple',
        'cherry' => 'red',
);

// Replace lemon and lime with apple
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red'));

// Replace cherry with strawberry
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));
?>

Note: I have not tested this with negative offsets and lengths.
up
18
daniele centamore
17 years ago
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;
      
       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             } 

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;
         
       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             } 
   
       return $new_array;
 }  

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
up
13
StanE
10 years ago
array_splice() does not preserve numeric keys. The function posted by "weikard at gmx dot de" won't do that either because array_merge() does not preserve numeric keys either.

Use following function instead:

<?php
function arrayInsert($array, $position, $insertArray