タイトルの通りです。
まずはサンプルコードの実行結果をご覧ください。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>php 様々な演算子</title> <link rel="stylesheet" href="../style.css"> </head> <body> <?php $ope1 = 10; $ope2 = 2; $num1 = $ope1 + $ope2; $num2 = $ope1 - $ope2; $num3 = $ope1 * $ope2; $num4 = $ope1 / $ope2; $num5 = $ope1 % $ope2; ?> <table border="2"> <tr> <th>項目</th> <th>結果</th> </tr> <?php echo " <tr> <td>\$ope1</td><td>{$ope1}</td> </tr> <tr> <td>\$ope2</td><td>{$ope2}</td> </tr> <tr> <td>$ope1 + $ope2 </td><td>{$num1}</td> </tr> <tr> <td>$ope1 - $ope2 </td><td>{$num2}</td> </tr> <tr> <td>$ope1 * $ope2 </td><td>{$num3}</td> </tr> <tr> <td>$ope1 / $ope2 </td><td>{$num4}</td> </tr> <tr> <td>$ope1 % $ope2 </td><td>{$num5}</td> </tr> " ?> </table> </body> </html> |
四則演算とその結果が表示されています。一番下の「%」は
剰余演算子という演算子で、あまりを計算する演算子です。
サンプルコードでは、「10」を「2」で割った時の余りがでます。
つまり「0」と出力されます。
インクリメント・デクリメント演算子
基本的な四則演算以外にも、プログラムを作成するときに
使用する演算子があります。たとえば以下のようなものです。
$a++;
++演算子はインクリメント演算子(increment operator)といいます。
インクリメントとは、変数の値を1増やす演算のことをいいます。
上記のコードは変数$aの値を1加算する処理を行っています。
また、下記のように書いても同じ処理です。
$a = $a + 1;
と書いても大丈夫です。
それとは対になるもので、「--」はデクリメント演算子(decrement operator)といい、
「デクリメント」とは、、変数の値を1減産することです。
$a--;
下記のように書いても大丈夫です。
$a = $a - 1;
インクリメント・デクリメントはどう使う?
これらの演算子は、数値を1増減させるため、
なにかしらの処理の回数を数える時に使います。
後に、記事で書くfor文でよく使います。