Create a PHP Form with 2 fields Name and Hobbies
Description: Create a PHP form with 2 fields: Name and Hobbies. After the submit, show the name and the selected hobbies.
Rules and hints:
- Name: a text input.
- Hobbies: checkboxes with these options: Singing, Reading, Dancing, Travelling and Drawing.
- The user can select more than one hobby.
PHP program with a form and hobbies
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$hobbies = $_POST["hobbies"] ?? [];
if ($name === "") {
$message = "Please enter your name.";
} elseif (empty($hobbies)) {
$message = "Please select at least one hobby.";
} else {
$message = "The hobbies of " . htmlspecialchars($name) . " are: " . htmlspecialchars(implode(", ", $hobbies));
}
}
?>
<form method="post">
Name: <input type="text" name="name"><br><br>
Hobbies:<br>
<input type="checkbox" name="hobbies[]" value="Singing"> Singing
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Dancing"> Dancing
<input type="checkbox" name="hobbies[]" value="Travelling"> Travelling
<input type="checkbox" name="hobbies[]" value="Drawing"> Drawing<br><br>
<button type="submit">Submit</button>
</form>
<p><?php echo $message; ?></p>
Output:
When the name is Robin and Singing and Dancing are selected
The hobbies of Robin are: Singing, Dancing
How it works
- The checkboxes have the same name
hobbies[], so PHP collects all the checked values in an array. implode()joins the array values with commas.- The form and the PHP code are in the same file, and the code runs only after the form is submitted (POST).
htmlspecialchars()keeps the output safe.
Related: PHP Forms Handling.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |