Multiple Selection With PHP

Category: PHP, HTML
Reviewed by: Chiggins   
Reviewed on: Oct 28 2008
» Discuss this topic ( Posts)

The Code

 
<?php
if ( isset( $_POST['item'] ) ) {
    foreach ( $_POST['item'] as $item ) {
        echo "You selected item number " . $item . "<br />";
    }
}
?>

The Explanation

Here is where things get interesting. First the script checks if the global POST variable "item" has been set. If you recall from the HTML, the checkbox names were "item[]". So, $_POST['item'] is a variable array containing the checked checkbox's.

Next is a foreach loop. Basically what it does is loop through each value in the $_POST['item'] array, and assigns each value to the variable $item.

Finally, we echo a string for each value in $_POST['item'] saying which has been selected.