Echoing multiple checkbox values In PHP

2019-07-23 02:56发布

问题:

I am having trouble using $_GET with radio buttons.

4th<input type="checkbox" name="date" value="4th">
5th<input type="checkbox" name="date" value="5th">
6th<input type="checkbox" name="date" value="6th">

The user chooses what days they are available. Then I want to echo out what days the user selected:

<?php echo "You are available " . $_GET["date"] . "!"; ?>

The above code only echos out one. Not all three. Is there a way to do this?

回答1:

checkbox values are returned in an array as they share the same index, so you need to use name="date[]" in your HTML.

If you want to know more, just try to print_r($_GET['date']); and see what you get.

And you've tagged your question as radio so would like to inform you that radio and checkbox are 2 different things, radio returns single value, where checkbox can return multiple.



回答2:

Name will be an array

<input type="checkbox" name="date[]" value="4th" />
<input type="checkbox" name="date[]" value="5th" />
<input type="checkbox" name="date[]" value="6th" />

Then get value like this

<?php

echo "You are available ";
foreach($_POST["date"] as $value) {
    echo "$value";
}

?>


回答3:

You could give each input an id:

<input type="checkbox" id="date1" value="4th" />
<input type="checkbox" id="date2" value="5th" />
<input type="checkbox" id="date3" value="6th" />

Then echo it like this:

$date1 = $_GET["date1"];
$date2 = $_GET["date2"];
$date3 = $_GET["date3"];

<?php echo "You are available " . $date1. ",". $date2. ",". $date3. ",". "!"; ?>


回答4:

Xth<input type="checkbox" name="date[]" value="Xth">

You can use in php

$_POST['date'][0]
$_POST['date'][1]


回答5:

Please use array to get multiple value -

Code:

4th<input type="checkbox" name="date[]" value="4th">
5th<input type="checkbox" name="date[]" value="5th">
6th<input type="checkbox" name="date[]" value="6th">

<?php
   $date=$_GET['date'];
   foreach($date as $dt){
     echo "You are available " . $dt . "!<br>";
   }
?>

I am not checking above code. I guess it will work.