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
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?