PHPの勉強中2
本日の勉強内容4
配列要素に値を代入する
配列に値を記憶するには、添字を使って要素を指定し、値を代入する
配列要素に値を出力する
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>PHPの勉強中</title> </head> <body> <?php $product[0] = "鉛筆"; $product[1] = "消しゴム"; $product[2] = "定規"; $product[3] = "コンパス"; $product[4] = "ボールペン"; ?> <table border="6" width="450"> <tr><th>商品名</th></tr> <?php for($i=0; $i<5; $i++){ print("<tr><td>{$product[$i]}</td><tr>\n"); } ?> </table> </body> </html>
本日の勉強内容5
キーによる格納
配列の添字として文字列を使う
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>PHPの勉強中</title> </head> <body> <?php $stock["みかん"] = 80; $stock["いちご"] = 60; $stock["りんご"] = 22; $stock["もも"] = 50; $stock["くり"] = 57; ?> <table border="5" width="450"> <tr><th>在庫状況</th></tr> <?php print("<tr><td>みかんは{$stock["みかん"]}個です。</td></tr>\n"); print("<tr><td>いちごは{$stock["いちご"]}個です。</td></tr>\n"); print("<tr><td>りんごは{$stock["りんご"]}個です。</td></tr>\n"); print("<tr><td>ももは{$stock["もも"]}個です。</td></tr>\n"); print("<tr><td>くりは{$stock["くり"]}個です。</td></tr>\n"); ?> </table> </body> </html>
本日の授業内容6
キー値と繰り返し文
配列を扱う際、foreach文と呼ばれる特殊な繰り返し文を使うことができます
キー用の変数と値用の変数を用意し、配列のキーと値を格納することができます
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>PHPの勉強中</title> </head> <body> <?php $stock["ミカン"] = 80; $stock["イチゴ"] = 60; $stock["リンゴ"] = 22; $stock["モモ"] = 50; $stock["レモン"] = 75; ?> <table border="5" width="450"> <tr><th>商品名</th><th>在庫状況</th></tr> <?php foreach($stock as $name => $value){ print("<tr><td>{$name}</td><td>{$value}</td></tr>\n"); } ?> </table> </body> </html>