0
0

More than 1 year has passed since last update.

array_slice() で配列の一部を取得する(PHP)

Last updated at Posted at 2022-12-17

概要

配列の一部が取得できます。
戻り値は取得した配列になります。

文法

array_slice(array, offset, length, preserve_keys)

[必須] array:入力配列
[必須] offset:開始位置の指定
[任意] length:開始位置からいくつ値を取得するか
[任意] preserve_keys:キーを保存するか

使い方

<?php

$input = ["a", "b", "c", "d", "e"];

$slicedList = array_slice($input, 2); 
print_r($slicedList); // Array ( [0] => c [1] => d [2] => e )

$slicedList = array_slice($input, 2, 2);
print_r($slicedList); // Array ( [0] => c [1] => d )

// 連想配列でも利用可能。
$input2 = [
    "input" => "test1",
    "input2" => "test2",
    "input3" => "test3",
];

$slicedList2 = array_slice($input2, 1);
print_r($slicedList2); // Array ( [input2] => test2 [input3] => test3 )

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0