[php] Getting checkbox values on submit

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.

This question is related to php forms

The answer is


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

?>

(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

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

}

?>

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!";
    }
}
?>

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

    }

    ?>

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';
}

//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']);

Just for printing you can use as below :

print_r($_GET['color']);

or

var_dump($_GET['color']);

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.