How To Get Multiple Selected Values Of Select Box In PHP

In PHP, when you have a multiple select box (dropdown) that allows users to select more than one option, you need to handle the selected values as an array. This is accomplished by setting the name attribute with square brackets and using PHP's superglobal arrays to retrieve the values.

Method 1: Using $_POST with Array Name Attribute

The most common approach is to set the name attribute of the select element as an array using square brackets. This tells PHP to treat the submitted values as an array

HTML Form Structure

<form method="POST" action="">
  <select name="mySelect[]" multiple>
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
    <option value="Option 4">Option 4</option>
  </select>
  <input type="submit" value="Submit">
</form>

PHP Processing Code

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedOptions = $_POST['mySelect'];

    if (!empty($selectedOptions)) {
        foreach ($selectedOptions as $option) {
            echo $option . '<br>';
        }
    } else {
        echo 'No options selected.';
    }
}
?>
Option 1
Option 2
Option 3

Method 2: Using $_REQUEST Superglobal Array

You can also use the $_REQUEST superglobal array, which combines $_GET, $_POST, and $_COOKIE data. This method works regardless of the HTTP request method

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedOptions = $_REQUEST['mySelect'];

    if (!empty($selectedOptions)) {
        foreach ($selectedOptions as $option) {
            echo $option . '<br>';
        }
    } else {
        echo 'No options selected.';
    }
}
?>
Option 1
Option 2
Option 4

Key Points

  • Array Notation: Use square brackets [] in the name attribute (e.g., name="mySelect[]") to indicate an array.

  • Multiple Attribute: Add the multiple attribute to the select element to enable multiple selections.

  • Validation: Always check if the array is not empty before processing to avoid errors.

  • Security: Validate and sanitize the selected values before using them in your application.

Conclusion

Getting multiple selected values from a select box in PHP requires setting the name attribute as an array and using superglobal arrays like $_POST or $_REQUEST to retrieve the values. This approach provides a clean and efficient way to handle multiple selections in web forms.

Updated on: 2026-03-15T10:28:36+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements