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
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";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.