LoginSignup
0

More than 1 year has passed since last update.

PHPの関数でreturnを使って値を返してみましょう!

Last updated at Posted at 2021-11-13

関数でreturnを返す



PHP関数の中でreturnを使って値を戻してみます!

こちらの関数があったとします。

index.php
<?php
function sum($a, $b, $c) {
  echo $a + $b + $c;
}
sum(2, 3, 4);



ターミナルに以下を入力すると...

~$ php index.php



3つの値が計算されて出力されました!

~ $ php index.php
9~ $



returnで書き換えてみます

index.php
<?php
function sum($a, $b, $c) {
  return $a + $b + $c;
}
echo sum(2, 3, 4);



もう一度以下のターミナルを実行します!

~$ php index.php



同じ結果になりました!

~ $ php main.php
9~ $ 



では、returnを使うと便利になる方法を見ていきましょう!

何個か値を合算したい時にreturnを使っていきます。

index.php

<?php
function sum($a, $b, $c) {
  return $a + $b + $c;
}
echo sum(2, 3, 4) + sum(1, 2, 3) . PHP_EOL;



もう一度以下のターミナルを実行すると...

~$ php index.php



2つの計算が合算されました!

~ $ php index.php
15
~ $



return後の関数の中の処理だけ無視されるので注意しましょう ☆

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