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 1 year has passed since last update.

PHPで配列を関数の返り値として使ってみましょう!

Posted at

#関数の返り値に配列を渡す


返り値を配列にして仮引数に渡します。

以下の sum 関数があったとします。

index.php
<?php
function sum(...$numbers) {
  $total = 0;
  foreach ($numbers as $number) {
    $total += $number;
  }
  return $total;  //返り値
}
print_r(sum(1, 2, 3));

ターミナルに以下を入力します。
~$ php index.php

合計が出力されました。
~ $ php index.php
6~ $ 

3つの合計の平均値も一緒に出力されるように、

返り値を配列にします。

3つの合計値と、 合計値を個数で割るようにします。

index.php
<?php
function sum(...$numbers) {
  $total = 0;
  foreach ($numbers as $number) {
    $total += $number;
  }
  return [$total, $total / count($numbers)];   //返り値を配列にする
}
print_r(sum(1, 2, 3));

ターミナルに以下を実行します。
~$ php index.php

3つの合計値と平均値が出力されました。
~ $ php index.php
Array
(
    [0] => 6
    [1] => 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?