Skip to content

Instantly share code, notes, and snippets.

@rickdaalhuizen90
Last active July 23, 2018 19:04
Show Gist options
  • Save rickdaalhuizen90/1b8a9007464b137e81f32693e4f2caa5 to your computer and use it in GitHub Desktop.
Save rickdaalhuizen90/1b8a9007464b137e81f32693e4f2caa5 to your computer and use it in GitHub Desktop.
Check for leap years between 2 dates.
<?php
$startYear = 1990;
$endYear = 2017;
$yearsToCheck = range($startYear, $endYear);
foreach ($yearsToCheck as $year) {
$isLeapYear = (bool) date('L', strtotime("$year-01-01"));
if($isLeapYear === true) echo $year . " is a leap year <br>";
}
/*
1992is a leap year
1996is a leap year
2000is a leap year
2004is a leap year
2008is a leap year
2012is a leap year
2016is a leap year
*/
<?php
function findLeapYears()
{
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$startYear = $_POST['start-year'];
$endYear = $_POST['end-year'];
$result = [];
$yearsToCheck = range($startYear, $endYear);
if(!empty($startYear) && !empty($endYear))
{
foreach ($yearsToCheck as $year) {
$isLeapYear = (bool) date('L', strtotime("$year-01-01"));
if($isLeapYear === true) $result[] .= $year . "is a leap year";
}
}
return $result;
}
}
?>
<form method="post">
<input type="text" name="start-year">
<input type="text" name="end-year">
<input type="submit" name="submit">
</form>
<?php var_dump(findLeapYears()) ?>
<!--
array (size=7)
0 => string '1992is a leap year' (length=18)
1 => string '1996is a leap year' (length=18)
2 => string '2000is a leap year' (length=18)
3 => string '2004is a leap year' (length=18)
4 => string '2008is a leap year' (length=18)
5 => string '2012is a leap year' (length=18)
6 => string '2016is a leap year' (length=18)
-->
<?php
$startYear = 1990;
$endYear = 2017;
$yearsToCheck = range($startYear, $endYear);
foreach ($yearsToCheck as $year) {
$isLeapYear = (bool) date('L', strtotime("$year-01-01"));
printf(
'%d %s a leap year %s',
$year,
$isLeapYear ? 'is' : 'is not',
"<br>"
);
}
/*
1990 is not a leap year
1991 is not a leap year
1992 is a leap year
1993 is not a leap year
1994 is not a leap year
1995 is not a leap year
1996 is a leap year
1997 is not a leap year
1998 is not a leap year
1999 is not a leap year
2000 is a leap year
2001 is not a leap year
2002 is not a leap year
2003 is not a leap year
2004 is a leap year
2005 is not a leap year
2006 is not a leap year
2007 is not a leap year
2008 is a leap year
2009 is not a leap year
2010 is not a leap year
2011 is not a leap year
2012 is a leap year
2013 is not a leap year
2014 is not a leap year
2015 is not a leap year
2016 is a leap year
2017 is not a leap year
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment