Handling arrays from forms

HTML forms are capable of sending data in arrays. This is useful where the number of items which will be entered into the form is unknown. PHP can step through those arrays until there are no more values.

Copy the code from the above page into a new HTML page and create the second page as well (which will be a blank PHP page). Into the PHP page put:

print_r($_POST);
        

Make sure that the form action points to the second page.

When you use the pages you should see the contents of the POST variable. Note that the products are held in an array inside one of the POST array elements. In PHP arrays can hold other arrays.

To access the sub array (arrayexample in the above example page) you could do this:

$firstarrayexample=$_POST["product"][0];
$secondarrayexample=$_POST["product"][1];
        

However a better way would be to step through the array like this:

foreach($_POST["product"] as $key=>$value){
    echo "<p>Product $key is $value</p>";
}        
        

Replace the print_r with those two and check the results. FOREACH being used to extract variables from an array was described in the beginners PHP section

submit to reddit Delicious Tweet