How to Get Multiple Selected Values of the Select Box in PHP
The task of this tutorial is retrieving the multiple selected values of the selected box in PHP.
Go ahead to see the solution.
Using the Multiple Attribute of HTML
To meet the goal, you can use the multiple attribute of HTML.
Selecting multiple values of HTML replies upon the browser and the operating system.
So, below we demonstrate the actions to take:
- On windows, you should hold down + CTRL key for selecting the multiple option.
- On Mac, it is necessary to hold down the command key for selecting the multiple option.
An example of creating a list of items with HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form method="post" action="/form/submit">
<h4>SELECT SUJECTS</h4>
<!--Using multiple to select multiple value-->
<select name="subject" multiple size="6">
<option value="english">ENGLISH</option>
<option value="maths">MATHS</option>
<option value="computer">COMPUTER</option>
<option value="chemistry">CHEMISTRY</option>
<option value="geography">GEOGRAPHY</option>
<option value="italian">ITALIAN</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Now, let’s get to retrieving the multiple selected values from the list. You are required to use the form method and loop for getting the selected value:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<!--name.php to be called on form submission-->
<form method="post" action="/form/submit">
<h4>SELECT SUJECTS</h4>
<select name="subject[]" multiple size="6">
<option value="english">ENGLISH</option>
<option value="maths">MATHS</option>
<option value="computer">COMPUTER</option>
<option value="chemistry">CHEMISTRY</option>
<option value="geography">GEOGRAPHY</option>
<option value="italian">ITALIAN</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Checking if the form is submitted successfully
if (isset($_POST["submit"])) {
// Checking if any option is selected
if (isset($_POST["subject"])) {
// Retrieve each selected option
foreach ($_POST['subject'] as $subject) {
print "You selected $subject<br/>";
}
} else {
echo "Select an option first !!";
}
}
?>
So, in this snippet, we represented a handy method of getting multiple selected values of the selected box in PHP.