How to select multiple values from HTML select box and access it in PHP

Hello Readers,

I would to write a blog on selecting multiple values from a select box.

Consider the select box,

<form>
<p>Select your favorite Fruit</p> 
<select name="fruit">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="grapes">Grapes</option>
<option value="pine">Pineapple</option>
<option value="banana">Banana</option>
</select>

We get a select box with five options. User can select only one option from five.

Incase, if user wants to select multiple options the code will change as

<form method="post">
<p>Select your favorite Fruit</p> 
<select name="fruit[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="grapes">Grapes</option>
<option value="pine">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>

Now look at the highlighted line,

<select name="fruit[]" multiple> has a word multiple and the name is added with [].

This makes the name as array which stores multiple values.

In PHP we can access the multiple values by the following code.

<?php
    $fruits = $_POST['fruit'];
    print_r($fruits);
?>

Output will be a array with the selected values.

While selecting multiple values user has to press CTRL to select multiple values.

Thanks

Nagarajan
Follow me

Nagarajan

Web Developer at Energy Alternatives India
I'm interested in developing Web applications andkeen on learning new technologies.

View Nagarajan's Profile
Nagarajan
Follow me

Latest posts by Nagarajan (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *