PHP understanding a small snippet code for extracting checkbox values - php

I have a snippet of PHP code, it works but I was curious to know why.
Green: <input type="checkbox" name="color[]" value="green" />
Black: <input type="checkbox" name="color[]" value="black" />
White: <input type="checkbox" name="color[]" value="white" />
Blue: <input type="checkbox" name="color[]" value="blue" />
Red: <input type="checkbox" name="color[]" value="red" />
then here is what I don't get for this PHP code below, how is $colors an array, I thought you have to at least have $colors[] = $_POST['color'].
if (isset($_POST['color'])) {
$colors = $_POST['color'];
}
echo $colors[0];
Thanks for helping me better understand this.

In HTML, every element with [] in its name is gonna be treated as an array.
Useful in cases like:
Choose your interests<br/>
<input type='checkbox' name='interests[]' value='Fashion'> Fashion
<input type='checkbox' name='interests[]' value='Cars'> Cars
<input type='checkbox' name='interests[]' value='Health'> Health
<input type='checkbox' name='interests[]' value='Programming'> Programming
Now you will acces them as an array in php:
$_POST['interests'][0] //-> Fashion

You don't need to explicitly add [] in PHP. Notice that you don't even need to define the type! This is PHP :)
$_POST['color'] is an array, so $colors will also be!
Read: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Edit
In PHP, if you write $colors[] = $var, you are actually adding $var to the end of that array. If the array is empty, $colors[0] == $var.
$colors = $_POST['color']; // $colors receives the array
$colors[] = $_POST['color']; // $colors[0] receives the array, if $colors was empty
More info: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

Related

Get each chekbox group values into separate variables upon form submission

I have multiple checkbox groups, and once the form is submitted, I want each group of checkboxes that were selected to be added to their own variable.
This is the form:
<form action="" method="get">
<p>apple <input type="checkbox" value="apple" name="fruits[]" /></p>
<p>orange <input type="checkbox" value="orange" name="fruits[]" /></p>
<p>peach <input type="checkbox" value="peach" name="fruits[]" /></p>
<br>
<p>red <input type="checkbox" value="red" name="colors[]" /></p>
<p>green <input type="checkbox" value="green" name="colors[]" /></p>
<p>blue <input type="checkbox" value="blue" name="colors[]" /></p>
<br>
<p>chicken <input type="checkbox" value="chicken" name="meats[]" /></p>
<p>pork <input type="checkbox" value="pork" name="meats[]" /></p>
<p>lamb <input type="checkbox" value="lamb" name="meats[]" /></p>
<button>submit</button>
</form>
And this is my code:
$string = 'fruits,colors,meats';
$str_array = explode(',', $string);
foreach ($str_array as $value) {
if (isset($_GET[$value])) {
$group_name = $_GET[$value];
foreach ($group_name as $group_item) {
$group_string .= ' ' . $group_item;
}
}
}
echo $group_string;
With that code, if I choose for example the first checkbox in each group and hit submit, I will get the following value of $group_string = apple red chicken in one string.
What I get does make sense to me as per the code I wrote, but what I want is for each option group to have its own variable to which its values are asigned, so what I want is to get is the following (assuming I again chose the first option from each group):
$fruits = 'apple';
$colors = 'red';
$meats = 'chicken';
But I don't know how to rewrite it so I get that. Also, the number of options groups is not known upfront, it has to happen dynamically.
Ok, I took the liberty of rewriting part of your php for my convenience but here it is
your new and improved php file
<?php
// assume we know beforehand what we are looking for
$groups = explode(',','fruits,colors,meats');
foreach ($groups as $group) {
if (isset($_GET[$group])) {
$vv = array();
foreach ($_GET[$group] as $item) $vv[] = $item;
$$group = implode(' ',$vv);
}
}
var_dump($fruits,$colors,$meats);
?>
I used a construct in PHP called variable variables. This is actually an almost identical answer as the one #Lohardt gave. I hope this can help you out. If it doesn't then post me a comment
You could do something like:
<input type="checkbox" value="apple" name="groups[fruits][]" />
<input type="checkbox" value="apple" name="groups[colors][]" />
<input type="checkbox" value="apple" name="groups[meats][]" />
Your $_POST will look like this:
Array
(
[groups] => Array
(
[fruits] => Array
(
[0] => apple
)
[colors] => Array
(
[0] => red
)
)
)
And it should be simple to use a foreach loop to get the keys and values.
Edit: then you can assign the value to variables like this:
${$key} = $value;
and use it you would do any variable:
echo $color;

checkbox array only returning one result

I have built a form that has a checkbox input array (saving to an array). However, when I POST it and retrieve the results, it only offers the last selection.
<input type="checkbox" value="Friendly" name="quest[9]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[9]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[9]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[9]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[9]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[9]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[9]"> Genuine<br>
For example, say I chose "Friendly", "Efficient", and "Genuine".
When I POST it over to a PHP document and run
print_r($_POST['quest']);
I only receive
Array ( [9] => Genuine )
back so "Genuine" is the only item I get back. Is there a way to fix this? What have I done wrong?
This is the 9th question on the survey, so changing the name unfortunately is not an option. Is there any way to combine the results to that single array separated by commas? I could always explode on the php side.
All your checkboxes have the same name, make them unique
<input type="checkbox" value="Friendly" name="quest[3]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[4]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[5]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[6]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[7]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[8]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[9]"> Genuine<br>
or use empty square brackets so php will treat the inputs as an array
<input type="checkbox" value="Friendly" name="quest[]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[]"> Genuine<br>
use quest[] in name instead of quest[9].
also in php part use this to add multiple choices .
<?php
$quest = implode(',',$_post['quest']);
print_r($quest);
?>
Happy coding!!
I'm posting a new answer about your comments on the previous one:
Since you must keep quest[9] as the organization for the checkbox array..
You may want to try and make it a more complex array, where each <input> has name="quest[9][1]", name="quest[9][2]" and so on.
And find the contents by
print_r($_POST['quest']);
again

combine checkbox values using php mysql

I having around 20 check boxes in my form as
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="2" />
<input type="checkbox" name="c3" value="3" />
<input type="checkbox" name="c4" value="4" />
i would like to these values to a database. I just thought rather than creating 20 fields in my database grab all the values at store in the db as 1,2,3,4 and then when querying to explode the values and display it accordingly using php.
can someone please tell me how am i supposed to concatenate the values 1,2,3,4 from the check fields when submitted so i can pass to the database.
i would appreciate if anyone can suggest a different effective way to achieve this using php.
You can change the name of the checkboxes to be the same, something like
<input type="checkbox" name="cb[]" value="1" />
<input type="checkbox" name="cb[]" value="2" />
Then access them via $_GET or $_POST via
if (isset($_POST['cb'])) {
$my_values = implode(",", $_POST['cb']);
}
If you want them sorted, then you will want to do something like this:
if (isset($_POST['cb'])) {
$my_values = $_POST['cb'];
sort($my_values);
$my_db_value = implode(',', $my_values);
}
For the record, I agree with #Shef in the case that the database can handle the extra load. Depending on when this information will be needed in a highly scalable solution, however, this is a perfectly acceptable way to handle this.
To answer your initial question, first off you need to name your checkboxes all the same name, so:
<input type="checkbox" name="box[]" value="1" />
....
<input type="checkbox" name="box[]" value="20" />
PHP script:
$boxes = $_POST['box'];
$values = implode(",", $boxes); // $values now has "1,2,3,4...", insert into table
A better way would be to have a separate table (see #Shef 's comment).

Get all values from checkboxes? [duplicate]

This question already has answers here:
Get $_POST from multiple checkboxes
(5 answers)
Closed 9 years ago.
Is there an easy way to get the values of multiple checkboxes and store them in the database?
<?php
if(isset($_POST['go'])){
$fruit = $_POST['fruit'].",";
echo $fruit;
// if you selected apple and grapefruit it would display apple,grapefruit
}
?>
<form method="post">
Select your favorite fruit:<br />
<input type="checkbox" name="fruit" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
<input type="checkbox" name="fruit" value="grapefruit" id="grapefruit" /><label for="grapefruit">Grapefruit</label><br />
<input type="submit" name="go" />
</form>
If you give the checkboxes the same name, ending in [], the values are returned as an array.
<input type="checkbox" name="fruit[]" value="apple" />
<input type="checkbox" name="fruit[]" value="grapefruit" />
Then in PHP ...
if( isset($_POST['fruit']) && is_array($_POST['fruit']) ) {
foreach($_POST['fruit'] as $fruit) {
// eg. "I have a grapefruit!"
echo "I have a {$fruit}!";
// -- insert into database call might go here
}
// eg. "apple, grapefruit"
$fruitList = implode(', ', $_POST['fruit']);
// -- insert into database call (for fruitList) might go here.
}
PS. please forgive the obvious error, that this example will potentially shout "I have a apple" ... I didn't think to make the example smart enough to determine when to use "a", and when to use "an" :P
Name your input like this :
<input type="checkbox" name="fruit[]" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit[]" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
Then iterate on the $_POST['fruit'] :
if(isset($_POST['fruit']) && !empty($_POST['fruit']))
foreach($_POST['fruit'] as $fruit) echo $fruit;
To add on to the other solutions...
implode and explode can be used in PHP to convert your array of fruit[] into a comma seperated list.
$valueToStoreInDB = implode(",",$_POST['fruit']);
$fruitAsAnArrayAgain[] = explode(",",$dbvalue);
Once you have your comma separated list, a good data type to represent the checkboxes in MySQL would be SET, and you can paste your comma seperated list right into your insert statement.

determine whether checkbox is checked php $_GET

I just want to have php determines whether a checkbox is checked, but I am running into a problem of getting the right return. Help please.
My html code
<label>
<input name="Language" type="checkbox" id="aa" checked="checked" />
One</label>
<label>
<input name="Language" type="checkbox" id="bb" />Two</label>
<label>
<input type="checkbox" name="Language" id="cc" />Three</label>
I pass the values to php by the $_GET method
my php code:
$aa=$_GET["aa"];
$bb=$_GET["bb"];
$cc=$_GET["cc"];
echo $aa."<br>";
echo $bb."<br>";
echo $cc."<br>";
the output is
true
false
false
I next want to just determine if each box is checked and if so, do something.
if ($aa == true) { $abc="checked";}
else { $abc="not checked"; }
if ($bb == true) { $cde="checked";}
else { $cde="not checked"; }
if ($fgh == true) { $fgh="checked";}
else { $fgh="not checked"; }
But the if statements always return true, even if the box is not checked. I tried variations of "===" and "!=", but it does not seem to work.
TIA
if (isset($_GET['checkbox_name'])) { ... }
Form controls (with the exception of file inputs, and with some special rules for image inputs) always submit strings. There is no concept of a boolean in a query string or a form encoded POST body.
The id is irrelevant — only the name and value matter (at least as far as PHP is concerned).
Since you haven't given them values they will, IIRC, default to on so if you are doing a comparison you should look for that. Looking with isset is simpler though. This is somewhat beside the point though, since your example gives them all the same name and value, so you can't differentiate between them.
Additionally, due to an oddity of the PHP form data parser, you have to end the with [] if you want multiple elements with the same name.
You probably want to do something like this:
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value="One" />
One</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value="Two" />Two</label>
<label>
<input type="checkbox" name="Language[]" id="cc" value="Three" />Three</label>
Important: Note the addition of values and the change in name.
Then in PHP $_GET['Language'] will be an Array of the values of the checked checkboxes, which you can loop over.
Try isset()
I think your HTML code should be like
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value ="1" />One
</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value ="2" />Two
</label>
<label>
<input name="Language[]" type="checkbox" id="cc" value ="3" />Three
</label>
and then by using something like
$count = count($_GET["Language"]); you can count the number of checkboxes checked.
Or do
$arr = $_GET["Language"]; //$arr is an array that contains the values of the checked checkboxes
Then you can foreach over the array
foreach( $arr as $item)
{
echo $item . "</br>"; /* Will print 1,2 and 3 (mind newlines)*/
}
In my PHP I got it from $_POST['checkbox_name'], and I found that the variable had the value on when the box was checked (i.e. it existed even if the checkbox was clear).

Categories