0
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 3 years have passed since last update.

PHP 複数の値を返す関数を定義する

Last updated at Posted at 2021-07-03

目的

  • 複数の値を返す関数を定義する方法をメモ的にまとめる

情報

  • 筆者は下記サービスを使って記事内で紹介するソースの動作確認を行った。

方法

  • 下記のように戻り値を配列状にして上げることで複数の値を返す関数を定義する事ができる。

    function returnStr()
    {
        $str_1 = '1つ目の文字列';
        $str_2 = '2つ目の文字列';
    
        return [$str_1, $str_2];
    }
    
  • 下記のように記載することで戻り値を配列状に取得する。

    function returnStr()
    {
        $str_1 = '1つ目の文字列';
        $str_2 = '2つ目の文字列';
    
        return [$str_1, $str_2];
    }
    
    $returnStrArray = returnStr();
    
    var_dump($returnStrArray);
    
  • 下記のようにlist戻り値の取得にlist関数(厳密には関数ではない)を用いるとそれぞれの戻り値各々を別々の変数へ格納する事ができる。

    function returnStr()
    {
        $str_1 = '1つ目の文字列';
        $str_2 = '2つ目の文字列';
    
        return [$str_1, $str_2];
    }
    
    list($returnStr_1, $returnStr_2) = returnStr();
    
    var_dump($returnStr_1);
    var_dump($returnStr_2);
    

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?