I am starting to learn PHP and and I'm stuck with this exercise... Here is the user experience we aim for : First, users see a form asking for their age :
Please type your age : __
When they submit the form, the page displays the right message:
if age is less than 12 years old, display "Hello kiddo!"
if age is between 12 and 18 years old, display "Hello Teenager !"
if age is between 18 and 115 years old, display Hello Adult !"
if age is beyond 115 years old, display "Wow! Still alive ? Are you a robot, like me ? Can I hug you ?"
Have both the form and the processing script in the same file. Use the GET method.
Here is a headstart.
// 3. "Different greetings according to age" Exercise
if (isset($_GET['age'])){
// Form processing
}
// Form (incomplete)
?>
<form method="get" action="">
<label for="age">...</label>
<input type="" name="age">
<input type="submit" name="submit" value="Greet me now">
</form>
I really don't know how to use the isset in this function :-( Can anyone give me a little push? It would be welcome! Thanks!
Here is the explanation of isset()
:
Determines if a variable is declared and is different than null.
So in your case you are just checking if $_GET['age']
has been set. If it is you would print a message depending on the input, otherwise the if
statement will be skipped:
<?php
if (isset($_GET['age']) && ctype_digit($_GET['age'])) {
$age = $_GET['age'];
if($age > 0 && $age <= 12) {
echo 'Hello kiddo!';
} else if($age > 12 && $age < 18) {
echo 'Hello Teenager !';
} else if($age >= 18 && $age <= 115) {
echo 'Hello Adult !';
} else if($age > 115) {
echo 'Wow! Still alive ? Are you a robot, like me ? Can I hug you ?';
}
}
?>
<form method="get" action="">
<label for="age">Please type your age: </label>
<input type="text" id="age" name="age" value="" />
<input type="submit" name="submit" value="Greet me now">
</form>
I also added a type="text"
attribute to your input element as well as an id
which the <label>
uses to refer to the proper element using it's for
attribute.
Note: the ctype_digit()
method above checks if a variable has numeric characters. This is optional and can be removed, although it helps to make sure that the correct value types have been passed.