Getting checkbox values on submit

PhpForms

Php Problem Overview


I have 6 options, I want to get the checked values to store them in variable on second page. How do I go on doing that?

<form action="third.php" method="get">
    <!-- Choices -->
    Red     <input type="checkbox" name="color[]" id="color" value="Red">
    Green   <input type="checkbox" name="color[]" id="color" value="Green">
    Blue    <input type="checkbox" name="color[]" id="color" value="Blue">
    Cyan    <input type="checkbox" name="color[]" id="color" value="Cyan">
    Magenta <input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow  <input type="checkbox" name="color[]" id="color" value="Yellow">
    Black   <input type="checkbox" name="color[]" id="color" value="Black">
    <!-- Submit -->
    <input type="submit" value="submit">
</form>

And third.php page :

$color = $_GET['color'];
 
echo 'The color is '.$color;

If I remove [], I get the color is on, when I do it like color[] I get a notice saying :

> Array to string conversion

What I want is the value of checked, checkboxes so I can store it in variable.

Php Solutions


Solution 1 - Php

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.";
}

?>

Solution 2 - Php

(It's not action="get" or action="post" it's method="get" or method="post"

Try to do it using post method:

<form action="third.php" method="POST">
    Red<input type="checkbox" name="color[]" id="color" value="red">
    Green<input type="checkbox" name="color[]" id="color" value="green">
    Blue<input type="checkbox" name="color[]" id="color" value="blue">
    Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
    Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
    Black<input type="checkbox" name="color[]" id="color" value="black">
    <input type="submit" value="submit">
</form>

and in third.php

or for a pericular field you colud get value in:

$_POST['color'][0] //for RED
$_POST['color'][1] // for GREEN

Solution 3 - Php

What i suggest is , its better to use post than get. here are some difference between post VS get

Some notes on GET requests:

  1. GET requests can be cached
  2. GET requests remain in the browser history
  3. GET requests can be bookmarked
  4. GET requests should never be used when dealing with sensitive data
  5. GET requests have length restrictions
  6. GET requests should be used only to retrieve data

Some notes on POST requests:

  1. POST requests are never cached
  2. POST requests do not remain in the browser history
  3. POST requests cannot be bookmarked
  4. POST requests have no restrictions on data length

HTML Code

            <html>
	<head></head>
	<body>
	<form action="output.php" method="post">
	Red<input type="checkbox" name="color[]" id="color" value="red">
	Green<input type="checkbox" name="color[]" id="color" value="green">
	Blue<input type="checkbox" name="color[]" id="color" value="blue">
	Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
	Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
	Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
	Black<input type="checkbox" name="color[]" id="color" value="black">
	<input type="submit" value="submit">
	</form>
	<body>
	</html>

PHP code

	<?php

	
	if(isset($_POST['color'])) {
    $name = $_POST['color'];

	echo "You chose the following color(s): <br>";
	foreach ($name as $color){
	echo $color."<br />";
	}} // end brace for if(isset

	else {

	echo "You did not choose a color.";

	}

	?>

Solution 4 - Php

It's very simple.

The checkbox field is like an input text. If you don't write anything in the field, it will say the field doesn't exist.

<form method="post">
	<input type="checkbox" name="check">This is how it works!<br>
	<button type="submit" name="submit">Submit</button>
</form>
<?php
if(isset($_POST['submit'])) {
	if(!isset($_POST['check'])) {
		echo "Not selected!";
	}else{
		echo "Selected!";
	}
}
?>

Solution 5 - Php

foreach is the best way to get array of values.

here the example code: html code:

<form action="send.php" method="post">
    Red<input type="checkbox" name="color[]" id="color" value="red">
    Green<input type="checkbox" name="color[]" id="color" value="green">
    Blue<input type="checkbox" name="color[]" id="color" value="blue">
    Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
    Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
    Black<input type="checkbox" name="color[]" id="color" value="black">
    <input type="submit" value="submit">
</form>

phpcode:

<?php

$name = $POST['color'];



foreach ($name as $color){ 
    echo $color."<br />";
}

?>

Solution 6 - Php

Just for printing you can use as below :

print_r($_GET['color']);

or

var_dump($_GET['color']);

Solution 7 - Php

I think the value for the $_POST['color'] should be read only after checking if its set.

<?php


    if(isset($_POST['color'])) {
      $name = $_POST['color'];  

    echo "You chose the following color(s): <br>";
    foreach ($name as $color){
   echo $color."<br />";
  }} // end brace for if(isset

else {

echo "You did not choose a color.";

}

?>

Solution 8 - Php

Perhaps a better way is using the php function in_array() like this:

$style='V';//can be 'V'ertical or 'H'orizontal
$lineBreak=($style=='V')?'<br>':'';
$name='colors';//the name of your options
$Legent="Select your $name";//dress it up in a nice fieldset with a ledgent
$options=array('red','green','blue','orange','yellow','white','black');
$boxes='';//innitiate the list of tickboxes to be generated
if(isset($_REQUEST["$name"])){ 
//we shall use $_REQUEST but $_POST would be better
   $Checked=$_REQUEST["$name"];
}else{
   $Checked=array();
}
foreach($options as $option){
$checkmark=(in_array($option,$Checked))?'checked':'';
$nameAsArray=$name.'[]';//we would like the returned data to be in an array so we end with []
$boxes.=($style=='V')?"<span class='label2' align='right'><b>$option : </b></span>":"<b>$option </b>";
$boxes.="<input style='width:2em;' type='checkbox' name='$nameAsArray' id='$option' value='$option' $checkmark >$lineBreak";
}

echo<<<EOF
<html>
<head></head>
<body>
<form name="Update" method="GET" action="{$_SERVER['PHP_SELF']}">\n
<fieldset id="tickboxes" style="width:25em;">
<legend>{$Legent}</legend>
{$boxes}
</fieldset>
<button type="submit" >Submit Form</button>
</form>
<body>
</html>
EOF
;

To start with we have created a variable $style to set if we want the options in a horizontal or vertical way. This will infrequence how we display our checkboxes. Next we set the $name for our options, this is needed as a name of the array where we want to keep our options. I have created a loop here to construct each option as given in the array $options, then we check each item if it should be checked in our returned form. I believe this should simplify the way we can reproduce a form with checkboxes.

Solution 9 - Php

//retrive check box and gender value
$gender=$row['gender'];
$chkhobby=$row['chkhobby'];
<tr>
    <th>GENDER</th>
    <td>
            Male<input type="radio" name="gender" value="1" <?php echo ($gender== '1') ?  "checked" : "" ;  ?>/>
            Female<input type="radio" name="gender" value="0" <?php echo ($gender== '0') ?  "checked" : "" ;  ?>/>
            
    </td>
</tr>
<tr>
    <th>Hobbies</th>
    <td>
        <pre><?php //print_r($row);
            
            $hby = @explode(",",$row['chkhobby']);
            //print_r($hby);
        ?></pre>
        read<input id="check_1" type="checkbox" name="chkhobby[]" value="read" <?php if(in_array("read",$hby)){?> checked="checked"<?php }?>>
        write<input id="check_2" type="checkbox" name="chkhobby[]" value="write" <?php if(in_array("write",$hby)){?> checked="checked"<?php }?>>
        play<input id="check_4" type="checkbox" name="chkhobby[]" value="play" <?php if(in_array("play",$hby)){?> checked="checked"<?php }?>>


    </td>
    </tr>
//update
$gender=$_POST['gender'];
$chkhobby = implode(',', $_POST['chkhobby']);

Solution 10 - Php

If you want to turn specific values in to new variables if they have been selected:

// Retrieve array color[] and set as variable    
$colors = $_GET['color'];
// Use array_search to find the key for "red"
$key_red = array_search('red', $colors);
// If "red" exists, the key will be an integer (or FALSE)
if (is_int($key_red)) {
    $red_color = 'Red was selected';
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlocalhostView Question on Stackoverflow
Solution 1 - PhpFunk Forty NinerView Answer on Stackoverflow
Solution 2 - PhpRahulView Answer on Stackoverflow
Solution 3 - PhpSathya BamanView Answer on Stackoverflow
Solution 4 - Phpuser9558267View Answer on Stackoverflow
Solution 5 - PhpmanikandanpachaiyappanView Answer on Stackoverflow
Solution 6 - PhpVaibhavraj RohamView Answer on Stackoverflow
Solution 7 - PhpBlacboyView Answer on Stackoverflow
Solution 8 - PhpCor CoolView Answer on Stackoverflow
Solution 9 - PhpjigarView Answer on Stackoverflow
Solution 10 - Phpuser8890598View Answer on Stackoverflow