LoginSignup
0

More than 3 years have passed since last update.

return(返り値)を複数返す方法

Last updated at Posted at 2020-06-05

返り値を複数返す方法とは!?

こんにちは、徳永です

returnの概念がやっと理解できたかな?と思った矢先にこんな問題が

関数内で値を2つ定義し、その二つの値を返り値に入れて
出力してください!

ふむふむ・・・

返り値を2つね、楽勝!!


function test()
{
    $num_1 = 100;

    $num_2 = 200;

    return $num_1, $num_2;
}

echo test();//エラー

あれ、構文エラー???

複数返り値にもたすことはできないのかな?

ならばこれで・・・


function test()
{

$array = [
    $num_1 = 100,
    $num_2 = 200
];
    return $array;
}

echo test()[0];  //100
echo test()[1];  //200


なるほど

返り値を二つ以上返したい場合は配列に入れて返せばいいのですね!

では試しに・・・


function test()
{
    $i = 0;

while ($i < 100) {
    $array[$i] = $i;
    $i++;
}
    return $array;
}

var_dump(test());

//array(100) {
//  [0]=>
//  int(0)
//  [1]=>
//  int(1)
//  [2]=>
//  int(2)
//  [3]=>
//  int(3)...........

何個でも返り値を持たせることができそうですね

以上、return(返り値)を複数返す方法でした

Twitterやってます、よかったらフォローお願いします!
https://twitter.com/tokuppee15

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