In PHP programming language, control structures like If, Else, and Elseif are very useful tools that allow you to control the execution flow of your program based on different conditions. These tools come into play when the user needs to display a specific message based on the age of a user.
Let’s start with a simple example. Suppose you want to evaluate the age of a user and display messages based on their age. For instance, you can say that if the user is younger than 18 years, they cannot access the adult page. If age is between 18 and 60, you would show a welcome message, and if the user is older than 60, you would send a different specific message.
In PHP, this task can be accomplished quite easily using If, Else, and Elseif statements. Below is an example showing these methods in action.
Imagine you have a form that captures the user's age and based on that, it decides which path to take.
<?php
$age = 25; // Assume the age is being captured from the form
if ($age < 18) {
echo "You do not have access to the adult page.";
} elseif ($age >= 18 && $age <= 60) {
echo "Welcome to our page!";
} else {
echo "We hope you have a good experience.";
}
?>
Code Explanation
$age = 25;
The user's age is captured from the form and stored in the variable $age
. if ($age < 18)
The first condition checks if the user's age is less than 18. echo "You do not have access to the adult page.";
If the above condition is true, this message is displayed. elseif ($age >= 18 && $age <= 60)
In this case, if this condition is true, the second message will be displayed. echo "Welcome to our page!";
This is the welcome message for users who fall between the ages of 18-60. else
Regardless of the other two conditions being false, the last message will be displayed. echo "We hope you have a good experience.";
This is the final message for users older than 60.