Quantcast
Channel: 配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 834

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

$
0
0
関数の返り値に配列を渡す 返り値を配列にして仮引数に渡します。 以下の 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 ) ~ $

Viewing all articles
Browse latest Browse all 834

Trending Articles