A good method which is a favorite of mine and for many I'm sure, is to make use of foreach
which will output each color you chose, and appear on screen one underneath each other.
When it comes to using checkboxes, you kind of do not have a choice but to use foreach
, and that's why you only get one value returned from your array.
Here is an example using $_GET
. You can however use $_POST
and would need to make both directives match in both files in order to work properly.
###HTML FORM
<form action="third.php" method="get">
Red<input type="checkbox" name="color[]" value="red">
Green<input type="checkbox" name="color[]" value="green">
Blue<input type="checkbox" name="color[]" value="blue">
Cyan<input type="checkbox" name="color[]" value="cyan">
Magenta<input type="checkbox" name="color[]" value="Magenta">
Yellow<input type="checkbox" name="color[]" value="yellow">
Black<input type="checkbox" name="color[]" value="black">
<input type="submit" value="submit">
</form>
###PHP (using $_GET) using third.php
as your handler
<?php
$name = $_GET['color'];
// optional
// echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
?>
Assuming having chosen red, green, blue and cyan as colors, will appear like this:
red
green
blue
cyan
##OPTION #2
You can also check if a color was chosen. If none are chosen, then a seperate message will appear.
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
} else {
echo "You did not choose a color.";
}
?>
##Additional options:
To appear as a list: (<ul></ul>
can be replaced by <ol></ol>
)
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
echo "<ul>";
foreach ($name as $color){
echo "<li>" .$color."</li>";
}
echo "</ul>";
} else {
echo "You did not choose a color.";
}
?>