PHPの教科書10 2次元配列
複数のチェックボックスを配列として渡し、phpで値を表示する。
http://felica.boy.jp/textbook/lecture1-2-6.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>よく分かるPHPの教科書</title> </head> <body> <form action="lecture1-2-6.php" method="get"> <dl> <dt>ご予約希望日(複数選択可):</dt> <dd> <ul> <!-- name属性に[]をつけると配列になる --> <li><input id="reserve_1" type="checkbox" name="reserve[]" value="1/1"><label for="reserve_1">1月 1日</label></li> <li><input id="reserve_2" type="checkbox" name="reserve[]" value="1/2"><label for="reserve_2">1月 2日</label></li> <li><input id="reserve_3" type="checkbox" name="reserve[]" value="1/3"><label for="reserve_3">1月 3日</label></li> </ul> </dd> </dl> <input type="submit" value="送信する"> </form> </body> </html>
ご予約日:<br> <p>foreach文で取得</p> <?php //reserve配列の値を一つずつ取得 foreach($_REQUEST['reserve'] as $value) { print(htmlspecialchars($value, ENT_QUOTES) . '<br>'); } ?> <br> <p>for文で取得</p> <?php //[$i]で配列番号の取得 for($i=0; $i<count($_REQUEST['reserve']); $i++) { print(htmlspecialchars($_REQUEST['reserve'][$i], ENT_QUOTES) . '<br>'); } ?>