PHP array_slice()関数
例
3番目の配列要素からスライスを開始し、配列内の残りの要素を返します。
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
定義と使用法
array_slice()関数は、配列の選択された部分を返します。
注:配列に文字列キーがある場合、返される配列は常にキーを保持します(例4を参照)。
構文
array_slice(array, start, length, preserve)
パラメータ値
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start the slice.
0 = the first element.
If this value is set to a negative number, the function will start slicing that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies the length of the returned array.
If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
|
preserve | Optional. Specifies if the function should preserve or reset the keys. Possible values:
|
技術的な詳細
戻り値: | 配列の選択された部分を返します |
---|---|
PHPバージョン: | 4歳以上 |
PHP変更ログ: | 保持パラメータはPHP5.0.2で追加されました |
その他の例
例1
2番目の配列要素からスライスを開始し、2つの要素のみを返します。
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
例2
負の開始パラメーターの使用:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
例3
保存パラメーターをtrueに設定すると、次のようになります。
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
例4
文字列キーと整数キーの両方を使用する場合:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown");
print_r(array_slice($a,1,2));
$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown");
print_r(array_slice($a,1,2));
?>
❮PHP配列リファレンス