PHP 学習メモ 9

概要

 PHP 学習メモ。カレンダー関数の利用。

内容

  1. 月の日数を返す関数

1. 月の日数を返す関数

 cal_days_in_month は年と月を渡すとその月の日数を返す関数。

www.php.net

 次のコードで年と月を指定するフォームを作る:

<form method="POST">
  <table>
    <tr>
      <td>年を選択してください:</td>
      <td>
        <select name="year">
          <?php
            for ($i = 2000; $i < 2030; $i++) {
              $selected = (
                isset($_POST['year']) && $_POST['year'] == $i
              ) ? 'selected' : '';

              echo "<option value=$i $selected>$i</option>";
            }
          ?>
        </select>
      </td>
    </tr>
    <tr>
      <td>月を選択してください:</td>
      <td>
        <select name="month">
          <?php
            for ($i = 1; $i < 13; $i++) {
              $selected = (
                isset($_POST['month']) &&
                $_POST['month'] == $i
              ) ? 'selected' : '';

              echo "<option value=$i $selected>$i</option>";
            }
          ?>
        </select>
      </td>
    </tr>
  </table>
  <input type="submit" value="日数を出力" />
</form>

 上図ボタン押下後(POST 実行後)、プルダウンリストの値が初期値に戻ってしまう。これを回避するため、selected 属性を付与している。

 次のコードで月と年を日数に変換する処理を行う:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // 月の日数を取得
  $number = cal_days_in_month(
    CAL_GREGORIAN,
    $_POST['month'],
    $_POST['year']
  );

  echo "{$_POST['year']}{$_POST['month']} 月の日数は {$number} 日です";
}
?>