Tuesday, 28 February 2012

How to use multiple selection check boxes with PHP

A multiple selection checkbox will look like this:


In order to post each values properly, we need to use the name attribute as an array, like this,
 <select multiple name = "opts[]" size="4">
Now lets try whats being POSTed,
<?php
if(isset($_POST['submit']))
echo '<pre>';
 print_r($_POST);
 echo '</pre>';
?>
<html>
<head>
    <title>1</title>
</head>
<body>
 <form method="post">
  <select multiple name = "opts[]" size="4">
   <option value="1">One</option>
   <option value="2">Two</option>
  <option value="3">Three</option>
  <input type="submit" value="submit" name="submit" />
  </select>
 </form>
</body>
</html>
Gives a nice array like this:
Array
(
    [opts] => Array
        (
            [0] => 2
            [1] => 3
        )

    [submit] => submit
)

No comments:

Post a Comment