PHP array_splice()関数
例
配列から要素を削除し、新しい要素に置き換えます。
<?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);
?>
定義と使用法
array_splice()関数は、選択した要素を配列から削除し、新しい要素に置き換えます。この関数は、要素が削除された配列も返します。
ヒント:関数が要素を削除しない場合(length = 0)、置き換えられた配列は開始パラメーターの位置から挿入されます(例2を参照)。
注:置き換えられた配列のキーは保持されません。
構文
array_splice(array, start, length, array)
パラメータ値
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. |
技術的な詳細
戻り値: | 抽出された要素で構成される配列を返します |
---|---|
PHPバージョン: | 4歳以上 |
その他の例
例1
ページ上部の例と同じ例ですが、出力は返された配列です。
<?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));
?>
例2
長さパラメータを0に設定した場合:
<?php
$a1=array("0"=>"red","1"=>"green");
$a2=array("0"=>"purple","1"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
❮PHP配列リファレンス