Função PHP array_splice()
Exemplo
Remova elementos de uma matriz e substitua-os por novos elementos:
<?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);
?>
Definição e uso
A função array_splice() remove elementos selecionados de um array e os substitui por novos elementos. A função também retorna um array com os elementos removidos.
Dica: Se a função não remover nenhum elemento (comprimento=0), o array substituído será inserido a partir da posição do parâmetro inicial (veja o Exemplo 2).
Nota: As chaves na matriz substituída não são preservadas.
Sintaxe
array_splice(array, start, length, array)
Valores de parâmetro
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. |
Detalhes técnicos
Valor de retorno: | Retorna o array que consiste nos elementos extraídos |
---|---|
Versão do PHP: | 4+ |
Mais exemplos
Exemplo 1
O mesmo exemplo do exemplo na parte superior da página, mas a saída é a matriz retornada:
<?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));
?>
Exemplo 2
Com o parâmetro de comprimento definido como 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ Referência de array PHP