2
2

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)

Last updated at Posted at 2023-01-06

条件演算子のサンプルプログラムです。
全体プログラムです

    <!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>関数テスト(引数とデフォルト)</title>
  <style>
      .a {
        font-size:18px;
        color:#2F7;
        font-weight: bold;
      }
     
  </style>  
</head>
<body>
  <?php
    function calc($a,$b,$c) {
      $total = $a + $b + $c;
      // 条件演算子($total>=0ならそのまま、$total<0なら0を返す)
      return $total >= 0 ? $total : 0;
    }
    function show($num){
      echo "<p class=a>$num</p>";
    }
    $a = calc(40,200,70);
    show($a);
    $b = calc(-400,200,70);
    show($b);

  ?>

</body>
</html>

PHP部分です

    <?php
    function calc($a,$b,$c) {
      $total = $a + $b + $c;
      // 条件演算子($total>=0ならそのまま、$total<0なら0を返す)
      return $total >= 0 ? $total : 0;
    }
    function show($num){
      echo "<p class=a>$num</p>";
    }
    $a = calc(40,200,70);
    show($a);
    $b = calc(-400,200,70);
    show($b);

  ?>

条件演算子の部分です。

return $total >= 0 ? $total : 0;

条件演算子(三項演算子)は

条件式 ? True : False

で書きます。可読性の問題があるので使う場合を考えるとよいでしょう。

2
2
2

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?