PHP array_splice() Funzione
Esempio
Rimuovi elementi da un array e sostituiscilo con nuovi elementi:
<?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);
?>
Definizione e utilizzo
La funzione array_splice() rimuove gli elementi selezionati da un array e lo sostituisce con nuovi elementi. La funzione restituisce anche un array con gli elementi rimossi.
Suggerimento: se la funzione non rimuove alcun elemento (lunghezza=0), l'array sostituito verrà inserito dalla posizione del parametro iniziale (vedi Esempio 2).
Nota: le chiavi nell'array sostituito non vengono conservate.
Sintassi
array_splice(array, start, length, array)
Valori dei parametri
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. |
Dettagli tecnici
Valore di ritorno: | Restituisce la matrice composta dagli elementi estratti |
---|---|
Versione PHP: | 4+ |
Altri esempi
Esempio 1
Lo stesso esempio dell'esempio nella parte superiore della pagina, ma l'output è l'array restituito:
<?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));
?>
Esempio 2
Con il parametro di lunghezza impostato su 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ Riferimento all'array PHP