Jump to content

Checking for a Leap yeay


Imtiyaaz

Recommended Posts

Hi

 

Im having a bit of trouble with my leap_year() function. If I enter in any year it prints "Leap Year" even if I enter in a year that is not a leap year. Below is my form and php...Please assist

 

<form Method = "POST" ACTION = "leap.php">
<input type = "text" name = "year" />
<br><br>
<input type ="submit" name= "check_year" value="Check" />
</form>

<?php
error_reporting(0); // turn error messages off

//Declare variables
$Check = $_POST['check_year'];
$year = $_POST['year'];

	if (isset($_POST['check_year'])) {
		leap_year();

	}
  

function leap_year()
{
if((($year % 4) == 0) && ((($year % 100) != 0) || (($year % 400) == 0))){
	echo "Leap Year";
	}
	else{
		echo "Not a leap year";
	}

}

?>

Link to comment
https://forums.phpfreaks.com/topic/260239-checking-for-a-leap-yeay/
Share on other sites

Although the logic in your function is correct, you certainly used an over abundance of parens! however, there's no need to write your own logic for this. You can use PHP's checkdate() or even the date() function to do it for you.

 

function leap_year($year)
{
    if(checkdate(2, 29, $year))
    {
        echo "Leap Year";
    }
    else
    {
        echo "Not a leap year";
    }
}

 

or,more simply

function leap_year($year)
{
    echo (checkdate(2, 29, $year)) ? "Leap Year" : "Not a leap year";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.