PHP Array to String Conversion (favourite colours chosen by user)
Description: Write a PHP exercise for array to string conversion.
Rules and hints:
- Create a form that accepts a name and some colors (checkboxes).
- After the submit, the data goes to another page.
- Show the user name and the selected colors as a list.
- The name and at least one color are required.
Step 1: the form (index.html)
<form action="data.php" method="post">
Name: <input type="text" name="username" required><br><br>
Select your favourite colors:<br>
<input type="checkbox" name="colors[]" value="Red"> Red
<input type="checkbox" name="colors[]" value="Green"> Green
<input type="checkbox" name="colors[]" value="Blue"> Blue
<input type="checkbox" name="colors[]" value="Yellow"> Yellow<br><br>
<button type="submit">Send</button>
</form>
The name colors[] (with the square brackets) tells PHP to collect all the selected values in an array.
Step 2: data.php
<?php
$username = trim($_POST["username"] ?? "");
$colors = $_POST["colors"] ?? [];
if ($username === "" || empty($colors)) {
exit("Name and at least one color are required.");
}
echo "Hello " . htmlspecialchars($username) . "<br>";
echo "Your favourite colors: " . htmlspecialchars(implode(", ", $colors));
?>
Output:
When the name is Robin and Red and Blue are selected
Hello Robin
Your favourite colors: Red, Blue
How it works
$_POST["colors"]is an array of the checked boxes.implode(", ", $colors)converts the array to a text. See how to convert an array to a string.htmlspecialchars()protects the page from XSS.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| PHP Array to String Conversion (favourite colours chosen by user) |
| Interview Questions & Answers |
|---|
| No Content Found. |