1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHP 配列の先頭を取り出す

Posted at

概要

  • PHPにてインデックスを用いず配列の先頭を取り出す方法を簡単にまとめる。

方法

  • 本来配列の先頭を取得する場合、$array[0]などの方法でインデックスで指定する必要がある。

  • 今回はarray_shift()を用い、最初の要素だけを取得してみる。

    <?php
    $array = ['foo', 'var', 'hoge', 'piyo'];
    
    var_dump($array[0]);
    
    $first = array_shift($array);
    var_dump($first);
    
    var_dump($array);
    
  • 下記の様に出力される。

    string(3) "foo"
    string(3) "foo"
    array(3) {
      [0]=>
      string(3) "var"
      [1]=>
      string(4) "hoge"
      [2]=>
      string(4) "piyo"
    }
    

注意

  • array_shift()はあくまで「配列の最初の要素を配列から取り出す」なので、最初の要素が取り出された配列は、それまでインデックス1だったものがインデックス0に、インデックス2だったものがインデックス1に詰められるので注意する。

参考文献

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?