今日の学習
先日の年齢入力フォームの件の続きです。諸々修正した改良版のコードも掲載されていたので、こちらも写経して読んでいきます。(変数名、メッセージの内容を一部短縮しています)
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 | <?php if (isset($_POST["uranai"])) { $age = mb_convert_kana($_POST["age"],"a","EUC-JP"); $error_msg = array(); if (is_numeric($age) == false) { $error_msg[] = "please type numeric."; } elseif ($age < 1 || $age > 120) { $error_msg[] = "please input 1< and >120"; } if (!count($error_msg)) { $sorry_msg = "ng"; $uranai_msg[1] = "you are 10-19."; $uranai_msg[2] = "you are 20-29."; $uranai_msg[3] = "you are 30-39."; $uranai_msg[4] = "you are 40-49."; $sedai = floor($age / 10); if (isset($uranai_msg[$sedai])) { print($uranai_msg[$sedai]); } else { print($sorry_msg); } } } else { $age = 25; } ?> <html> <body> <?php if (count($error_msg)) { foreach($error_msg as $msg) { print($msg); } } ?> <form action = "sample_uranai2.php" method = "POST"> 年齢を教えてください: <input type = "text" name = "age" value = "<?php print(htmlspecialchars($age, ENT_QUOTES));?>"> <input type = "submit" name = "uranai" value = "submit"> </form> </body> </html> |
まず、入力された数字が全角だった場合に半角に変換するため、 mb_convert_kana() で処理した値を変数 $age に入れています。
変数 $error_msg という空の配列を用意しています。エラーの種類によって表示させるエラーメッセージを変えるけれども変数は一つ、ということですね。
is_numeric() が false 、つまり入力された値が数字ではない場合、また数字でも 1 未満もしくは 121 以上の場合はエラーとしています。演算子 || は or ですね。
if (!count($error_msg)) というところは、まず条件式の頭に ! が付いているので「もし条件式が false だったら」という意味になり、その条件式では count() で配列 $error_msg の要素数を調べています。
if 文では「要素数がゼロの配列」は false になるので、要するに $error_msg が空だったら、ということですね。
(つづく)