ITHACK
~ みんなのIT部門 ~
【PHP/演習問題】関数と戻り値[4]

【PHP/演習問題】関数と戻り値[4]

問題

月の末日を出力するプログラムを作成してください。
なお、下記条件を満たすものとします。

  • 年と月はコマンドライン引数で与える
  • 閏年判定のアルゴリズムはグレゴリオ暦に従う
  • 末日を求めるlast_day_of_month関数を作成する
    引数:年、月
    戻り値:末日
$ php practice.php 2022 1
2022年1月 : 31日
$ php practice.php 2022 2
2022年2月 : 28日
$ php practice.php 2024 2
2024年2月 : 29日
$ php practice.php 2027 9
2027年9月 : 30日

解答例

<?php

function is_leap_year( $year ) {
    
    if( $year % 4 == 0 && ( $year % 100 != 0 || $year % 400 == 0 ) ) {
        return true;
    }
    
    return false;
}

function last_day_of_month( $year, $month ) {
    
    $last_day_map = [
        1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
        7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31,
    ];
    
    $last_day = $last_day_map[$month];
    if( is_leap_year($year) && $month == 2 ) $last_day = 29;
    
    return $last_day;
}

$year = $argv[1];
$month = $argv[2];

$last_day = last_day_of_month($year, $month);

echo $year.'年'.$month.'月 : '.$last_day."日\n";

?>