In this post, we are going to see how to write a PHP program to print leap years between two selected years.
So basically we have to create a form with two inputs to collect the start year and end year and a submit button. After submitting, we need to loop between the start and end year and then find the leap years to print.
Here is the entire script, I am using bootstrap CSS to make the HTML form neat.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?php if(isset($_POST['submit'])){ //get the post values $starYear = $_POST['startyear']; $endYear = $_POST['endyear']; //define an array $leapYears = array(); //loop through between the selected years for($i=$starYear; $i <= $endYear; $i++){ if( (0 == $i % 4) and (0 != $i % 100) or (0 == $i % 400) ){ $leapYears[] = $i; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>PHP to print leap years!</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Load Bootstrap library for better UI look & feel --> <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" /> </head> <body> <div class="container"> <br /> <h2>PHP to print leap years!</h2> <br /> <div class="row"> <div class="col-lg-4"> <div class="input-group mb-4"> <form action="" method="post"> <div class="form-group"> <label for="startyear">Start Year</label> <input type="number" class="form-control" id="startyear" name="startyear" placeholder="Start Year" value="<?=(isset($starYear))? $starYear : '1990'; ?>" min="1900" max="2999"> </div> <div class="form-group"> <label for="endyear">End Year</label> <input type="number" class="form-control" id="endyear" name="endyear" placeholder="End Year" value="<?=(isset($endYear))? $endYear : '2020'; ?>" min="1900" max="2999"> </div> <button type="submit" name="submit" class="btn btn-primary">Submit</button> </form> </div> <div><strong>Leap years:</strong><br /> <!-- Print the result --> <?php if(isset($leapYears)){ foreach($leapYears as $leapyear){ print $leapyear."<br>"; } } ?> <div> </div> </div> </div> </body> </html> |
It’s a pretty simple PHP script, just read the comments in the above script to understand it.
You can always check the demo here before going through the script, Here is the demo of this program: