PHP Introduction | Form Submission Basics | Selecting Multiple Items in a select List

Now we understand the basic usage of form elements. However, there is still one thing we have not explained. It is “selecting multiple items with <select>.”

A list created with <select> can allow multiple selections by setting the multiple attribute. In this case, how can you check the selected items? The usual method does not work well. You need to use a small technique.

Let us look at a simple example.

<?php
    if ($_POST != null){
        $arr = $_POST['list1'];
        $result = "";
        foreach($arr as $item){
            $result .= $item . "\n";
        }
    } else {
        $result = "Please enter a value.";
    }
?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type"
            content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Hello PHP!</h1>
        <pre><?php
            echo htmlspecialchars($result);
        ?></pre>
        <form method="post" action="./index.php">
            <select name="list1[]" size="5" multiple>
                <option value="Windows">Windows</option>
                <option value="Mac OS">Mac OS</option>
                <option value="Linux">Linux</option>
                <option value="Android">Android</option>
                <option value="iOS">iOS</option>
            </select>
            <input type="submit">
        </form>
    </body>
</html>

Select several items in the form and submit it. The selected items are output above the form.

Here, the values from the selected list are obtained with $arr = $_POST['list1'];. Then the following kind of processing is performed.

foreach ($arr as $item) {
    $result .= $item . "\n";
}

In this way, foreach is used to take values from $arr in order and process them. In other words, $arr is an array. All selected items are passed as an array.

To receive data as this array, you also need to configure the form side. Look carefully at the <select> tag.

<select name="list1[]" size="5" multiple>

The multiple attribute is added so that multiple items can be selected. However, that is not the only point. The name is specified as name="list1[]". It is "list1[]" instead of "list1". By writing it this way, the value of list1 is passed not as ordinary text, but as an array of text values.

This “selecting multiple items from a list” is important, so make sure you understand it here.

Text Assignment Operator

There is another unfamiliar symbol here: .=. This operator appends the text on the right side to the end of the variable on the left side. In other words, A .= B has the same meaning as A = A . B. It is a simpler way to write that operation.