In this tutorial, we’ll write a simple PHP program to check if a person is eligible to vote based on their age. The eligibility criterion is straightforward: a person must be 18 years or older to be eligible for voting.
We’ll create a web form that asks the user to enter their age, and based on the input, the program will determine whether the person is eligible to vote or not.
Program Logic:
- The program prompts the user to enter their age using an HTML form.
- The form sends the age value to the PHP script using the
GET
method. - The PHP script checks if the entered age is greater than or equal to 18.
- If the age is 18 or more, the program will print “Eligible for Voting!”.
- If the age is less than 18, it will print “Not Eligible for Voting!”.
PHP Code:
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 | <html> <head> <title>PHP Voting Eligibility Test</title> </head> <body> <form method="get"> <input name="age" placeholder="Enter your age" type="number"><br><br> <input name="btn" type="submit" value="Submit Age"> </form> <?php // Check if the 'age' value is set in the GET request if (isset($_GET["age"])) { // Get the entered age $age = $_GET["age"]; // Display the entered age echo "<h2>Your Age: $age</h2>"; // Check eligibility for voting if ($age >= 18) { echo "<h1>Eligible for Voting!</h1>"; } else { echo "<h1>Not Eligible for Voting!</h1>"; } } ?> </body> </html> |
Explanation of the Code:
- HTML Form:
- The form contains a text input field for the user to enter their age (
<input name="age" placeholder="Enter your age" type="number">
). - The form uses the
GET
method to submit the entered data, sending it to the same PHP page. - The submit button (
<input name="btn" type="submit" value="Submit Age">
) triggers the submission of the form.
- The form contains a text input field for the user to enter their age (
- PHP Script:
- Input Retrieval: The PHP script checks if the
age
value is submitted using theisset()
function (if(isset($_GET["age"]))
). - Age Validation: The script retrieves the entered age from the
$_GET
array and compares it to 18. If the age is 18 or more, it prints “Eligible for Voting!”, otherwise it prints “Not Eligible for Voting!”.
- Input Retrieval: The PHP script checks if the
- Output:
- After the form submission, the webpage will display the entered age and show whether the person is eligible to vote based on the input.
Example Output:
If the user enters 20:
1 2 3 4 | Your Age: 20 Eligible for Voting! |
If the user enters 16:
1 2 3 4 | Your Age: 16 Not Eligible for Voting! |
Conclusion:
This simple PHP program demonstrates how to check whether a person is eligible to vote based on their age. By using basic form handling and conditional statements, we can easily create interactive web applications that perform real-time validation.
Write a program to check whether a person is eligible to vote or not in PHP
Output:
