Funkcja PHP array_splice()
Przykład
Usuń elementy z tablicy i zastąp je nowymi elementami:
<?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);
?>
Definicja i użycie
Funkcja array_splice() usuwa wybrane elementy z tablicy i zastępuje je nowymi elementami. Funkcja zwraca również tablicę z usuniętymi elementami.
Wskazówka: Jeśli funkcja nie usunie żadnych elementów (długość=0), zastąpiona tablica zostanie wstawiona od pozycji parametru start (patrz przykład 2).
Uwaga: klucze w zastąpionej tablicy nie są zachowywane.
Składnia
array_splice(array, start, length, array)
Wartości parametrów
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. |
Szczegóły techniczne
Wartość zwrotu: | Zwraca tablicę składającą się z wyodrębnionych elementów |
---|---|
Wersja PHP: | 4+ |
Więcej przykładów
Przykład 1
Ten sam przykład, co przykład na górze strony, ale wynikiem jest zwrócona tablica:
<?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));
?>
Przykład 2
Z parametrem długości ustawionym na 0:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮ Odniesienie do tablicy PHP