Funkce PHP array_splice().
Příklad
Odeberte prvky z pole a nahraďte je novými prvky:
<?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);
?>
Definice a použití
Funkce array_splice() odstraní vybrané prvky z pole a nahradí je novými prvky. Funkce také vrátí pole s odstraněnými prvky.
Tip: Pokud funkce neodstraní žádné prvky (délka=0), bude nahrazené pole vloženo z pozice počátečního parametru (viz příklad 2).
Poznámka: Klíče v nahrazeném poli se nezachovají.
Syntax
array_splice(array, start, length, array)
Hodnoty parametrů
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. |
Technické údaje
Návratová hodnota: | Vrátí pole sestávající z extrahovaných prvků |
---|---|
Verze PHP: | 4+ |
Další příklady
Příklad 1
Stejný příklad jako příklad v horní části stránky, ale výstupem je vrácené pole:
<?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));
?>
Příklad 2
S parametrem délky nastaveným na 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ PHP Array Reference