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で可変長引数を使ってみましょう!

Posted at

#可変長引数


渡された引数が何個になっても処理してくれる可変長引数を、

foreachと一緒に使います。

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

引数に可変長引数の 「 ... $ numbers 」を入れておきます。

foreach で $numbers の中身を一つづつ取り出して、

$total にプラスしていきます。

$total  を ...$numbersの仮引数に返します。


index.php
<?php
function sum(...$numbers) {
  $total = 0;
  foreach ($numbers as $number) {
    $total += $number;
  }
  return $total;
}
echo sum(1, 2, 3) . PHP_EOL;
echo sum(4, 5, 6, 7) . PHP_EOL;

echo sum (1, 2, 3) . PHP_EOL ; で実引数を渡します。

echo sum (4, 5, 6, 7) . PHP_EOL ; で個数を変えて実引数を渡してみます。

ターミナルで以下を実行します。

~$ php index.php

計算結果が出力されました!
~ $ php index.php
6
22
~ $ 
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?