Posting array of checkboxes in PHP - php

I have multiple checkboxes with names of adminMeta[], such as:
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
and so on and I also have text inputs like this too with the same names.
When the data is posted, I am looping through using a foreach loop:
foreach($_POST["adminMeta"] as $a => $b) {
}
inside the loop, I add/update the record in my database depending on whether it exists already or not.
But I am having some issues with checkboxes and knowing whether they are checked or not.
I have tried using if(isset($b)) but that hasn't worked.
How can I tell inside my loop, whether a checkbox is checked or not?

If a checkbox is not checked, then it is not a successful control.
If it is not a successful control, then it won't be included in the form data at all.
If it isn't in the form data, then it won't appear when you loop over the form data.
So
If it is in the form data, then it is checked
Otherwise it is not checked
Normally I'd approach this problem with something along the lines of:
$list_of_checkboxes = [ "name1", "name2" ];
Then generate the form with:
foreach ($list_of_checkboxes as $name) {
?>
<label>
<input type="checkbox"
name="adminMeta[]"
value="<?php echo htmlspecialchars($name); ?>">
<?php echo htmlspecialchars($name); ?>
</label>
<?php
}
Then test the data with:
foreach ($list_of_checkboxes as $name) {
if (in_array($name, $_POST['adminMeta'])) {
# Checked
} else {
# Not checked
}
}

Another approach would be to set hidden inputs before each check with default value of 0:
<input type="hidden" name="adminMeta[name1]" value="0" />
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="hidden" name="adminMeta[name2]" value="0" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
Now you will receive the data even if you don't check the checkboxes.

Related

How to check Checkbox not checked in foreach

I have html checkbox like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br />
<input type="checkbox" name="language[]" value="html" />HTML<br />
<input type="checkbox" name="language[]" value="java" />Java<br />
<input type="checkbox" name="language[]" value="c++" />C++<br />
<input type="submit" value="send" />
</form>
Now I want to detect the checkbox is not checked using this PHP
if($_POST)
{
if(empty($_POST['language']))
{
echo "bla";
}
else
{
foreach($_POST['language'] as $value)
{
echo 'Checked: '.$value.'
';
}
}
}
The output is always show the checbox checked.
My question is, how can I detect the checkbox is not checked?
Example I do not check PHP and Java.
You don't need to validate checkbox by checkbox in order to determine if they are checked or not, you won't get the unchecked checkboxes values at the time you send the form, so, sending the form like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br /> <!-- checked -->
<input type="checkbox" name="language[]" value="html" />HTML<br /><!-- checked -->
<input type="checkbox" name="language[]" value="java" />Java<br /><!-- unchecked -->
<input type="checkbox" name="language[]" value="c++" />C++<br /><!-- unchecked -->
<input type="submit" value="send" />
</form>
In your PHP, you will get an array as follows:
$_POST['languages'] = array("php", "html");
Now, lets say you have an array of all the values in order to check which ones you need to delete, and which ones you need to add, a rough code example would be as follows:
$allValues = array('php', 'html', 'java', 'c++');
$valuesForAdd = $_POST['language'];
$valuesForDeletion = array_diff($allValues, $valuesForAdd);
First you need the selectable items array in the backend:
$items = array('php','html','java','c++');
You have the posted (selected) languages array here:
$_POST['language']
Not selected languages array:
$not_selected_languages = array_diff($items,$_POST['language']);
I hope it helps.
Only 'checked' checkboxes get sent as parameters in a POST request.
If you want to know which aren't checked, you could have the value list stored on PHP side; then once you receive POST data - compare the array on PHP side with POST array.
$all_vals = array('php', 'c++', 'html', 'java');
$post_vals = $_POST['languages'];
foreach ($post_vals as $post_val)
if in_array($post_val, $all_vals)
$checkbox checked
else
$checkbox not checked
I assume this gives you enough liberty to do what you need.

Multiple Checkboxes array with checked and unchecked values

So i have this line of code that will repeat different times in a form.
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
The !checked show that the checkbox was checked and the !unchecked shows that the checkbox was not checked.
How can i create a php array to get values of checked and unchecked checkboxes in order like this :
array( 0 => checked, 1 => unchecked, 2 => checked, 3 => unchecked );
Momentarily i can get just the checked value with $_POST["checkbox"] but i cannot get the unchecked value.
First of all you need to put a value to your checkboxes:
<input type="checkbox" name="checkbox[]" value="checkboxNchecked" /> !checked
You can't really distinguish your checkboxes otherwise.
Then: Your checkboxes will either return a value if they are checked or will be ignored when they are unchecked. You will not get a NULL, FALSE or other value. It will simply not be transfered via POST/GET to your php script as if it wasn't in yout HTML code. This covers the topic: Does <input type="checkbox" /> only post data if it's checked?
If you know how many checkboxes are around and what they are called - no problemo señor - but if you don't, you'll need to find a way around. If you tell us what the nature of your checkboxes are, we can help you find a tailored solution.
you can use jquery and ajax. In your submit event get all values from the form and submit it by ajax. you can get unchecked value in jquery like this:
$("input:checkbox:not(:checked)")
or
if ($('#idOfYourCheckBox:checked').length > 0) {
//its checked
}
else {
//not checked
}
This will print only checked fields, because unchecked ones are not sent to server.
You will have to do some javascript and hidden field tricks.
Take a look here
Post the checkboxes that are unchecked
<input type="checkbox" name="checkbox[n1]" /> !checked
<input type="checkbox" name="checkbox[n2]" /> !unchecked
<input type="checkbox" name="checkbox[n3]" /> !checked
<input type="checkbox" name="checkbox[n4]" /> !sdsk
foreach($_POST['checkbox'] as $key => $value){
$checkbox[$key] = 'checked';
}
print_r($checkbox); // your new array
Solved:
Declaration of form...
<form id="form1" name="form1" method="post" action="xx.php" onSubmit="set_hidden_value()">
<input name="arrayofchecks" type="hidden" value="toset" />
...
OnSubmit:
function set_hidden_value()
{
var checkstring = "";
for (var i=0; i < $('#checkbox').length; i++)
{
if ($('#checkbox')[i].checked)
{
checkstring = checkstring + "1";
}
else
{
checkstring = checkstring + "0";
}
}
$('#arrayofchecks').val(checkstring);
And the result is a string with values checked and unchecked (1 and 0)...
In my case, i use ajax for intercept submit and do set_hidden_value here...
If you are using a server side language like PHP, there is an easier method than using hidden fields to supply default or writing javascript (both may fail if the user's device/browser doesn't support that method).
<input type="checkbox" value="choice1" name="checkbox[]" />
<input type="checkbox" value="choice2" name="checkbox[]" />
<input type="checkbox" value="choice3" name="checkbox[]" />
This method doesn't return unchecked items, but it specifically identifies which items were checked. Otherwise, if the checkboxes all have the same value, all you get is one, two or 3 values repeated with no idea which item was checked. However, assuming choice2 was checked with the above method, it's pretty easy then to figure out that item 1 and 3 therefore were not checked.
Please check below code.
$("button").click(function () {
var i=0;
var cbox=[];
$("input[name='cbox']").each(function () {
if($(this).is(':checked')) {
cbox[i++] = $(this).val();
}else{
cbox[i++] = "unchecked";
}
});
console.log(cbox);
i = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<button>Click</button>

Get POST data from multiple checkboxes?

Im trying to create a form using PHP and I cant seem to find a tutorial on what I need so thought Id ask on here.
I have a multiple checkbox option on my page...
<li>
<label>What service are you enquiring about?</label>
<input type="checkbox" value="Static guarding" name="service">Static guarding<br>
<input type="checkbox" value="Mobile Patrols" name="service">Mobile Patrols<br>
<input type="checkbox" value="Alarm response escorting" name="service">Alarm response escorting<br>
<input type="checkbox" value="Alarm response/ Keyholding" name="service">Alarm response/ Keyholding<br>
<input type="checkbox" value="Other" name="service">Other<input type="hidden" value="Other" name="service"></span>
</li>
I'm not sure however how to collect all checkbox values using POST method?
if i use
$service = $_POST['service'];
I only get 'other' returned
Name the fields like service[] instead of service, then you'll be able to access it as array. After that, you can apply regular functions to arrays:
Check if a certain value was selected:
if (in_array("Other", $_POST['service'])) { /* Other was selected */}
Get a single newline-separated string with all selected options:
echo implode("\n", $_POST['service']);
Loop through all selected checkboxes:
foreach ($_POST['service'] as $service) {
echo "You selected: $service <br>";
}
Currently it's just catching your last hidden input. Why do you have that hidden input there at all? If you want to gather information if the "Other" box is checked, then you have to hide the
<input type="text" name="other" style="display:none;"/>
and you can show it with javascript when the "Other" box is checked. Something like that.
Just make the name attribute service[]
<li>
<label>What service are you enquiring about?</label>
<input type="checkbox" value="Static guarding" name="service[]">Static guarding<br />
<input type="checkbox" value="Mobile Patrols" name="service[]">Mobile Patrols<br />
<input type="checkbox" value="Alarm response escorting" name="service[]">Alarm response escorting<br />
<input type="checkbox" value="Alarm response/ Keyholding" name="service[]">Alarm response/ Keyholding<br />
<input type="checkbox" value="Other" name="service[]">Other</span>
</li>
Then in your PHP you can access it like so
$service = $_POST['service'];
echo $service[0]; // Output will be the value of the first selected checkbox
echo $service[1]; // Output will be the value of the second selected checkbox
print_r($service); //Output will be an array of values of the selected checkboxes
etc...
<input type="checkbox" value="Other" name="service">Other<input type="hidden" value="Other" name="service"></span>
You've got a hidden input field with the same name as the checkbox. "later" fields with the same name as an earlier one will overwrite the previous field's values. This means that your form, as posted above, will ALWAYS submit service=Other.
Given the phrasing of your question in the html, it sounds more like you'd want a radio button, which allows only ONE of a group of same-name fields to be selected. Checkboxes are an "AND" situation, radio buttons correspond to "OR"

Checkbox "checked"-value jumps up to earlier array values, when array is empty

I have an array of checkboxes name="box[]". Through PHP I make sure that they're checked after they're submitted by echoing "checked='checked'" if they were checked at submit event.
Now, if I check the third box, the value jumps down to the first checkbox after submit, since the array was empty up until the third checkbox. Same, if I check the 2nd and 3rd checkbox, they jump down to 1st and 2nd after submit. This is the code I'm using:
<form method="post">
<input type="checkbox" name="box[]" value="true" <?php if ($box[0] == true) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="true" <?php if ($box[1] == true) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="true" <?php if ($box[2] == true) echo "checked='checked'"; ?>><br>
<p>
<input type="submit" value="Submit">
</form>
Try it at:
http://experiencerapanui.com/selecttest.php
Can I make the checkboxes fill up the array with a value "false" or whatever, if the box is unchecked? Which way should I go?
****** EDIT ******
Thanks to phant0m, I managed to come up with a solution:
<form method="post">
<input type="checkbox" name="box[]" value="1" <?php if (in_array("1", $box)) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="2" <?php if (in_array("2", $box)) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="3" <?php if (in_array("3", $box)) echo "checked='checked'"; ?>><br>
<p>
<input type="submit" value="Submit">
</form>
Putting unique values for the checkboxes, then if I find the value in the array $box[], the box is marked as checked.
This does not work, because only those checkboxes, that are checked, are being put into the $box array.
Either use different names, or different values to distinguish between them.
Consider this: You check the second and the third checkbox. In PHP, you will receive:
$_POST['box'] = array(0 => "true", 1 => "true");
You cannot know, which checkboxes have been checked, unless all of them are.
The POST value should start with isset, then !empty($array) determines if the POST value is an array and prevents a null array error when no options are selected.
&& is_array($_POST['box']) could be used in addition to !empty($_POST['box']) as well to check the validity of the array.
A variable is used in the following examples for the value field, as it makes it easier to define and populate inputs when using a foreach loop and may be sanitized if needed as a preventive measure.
It would probably be a good idea to sanitize the $_POST array also, and enclosing it in a function with the validation would allow it all to be called from the checkbox input and keep the input area tidy.
<input type="checkbox" name="box[]" value="<?php echo $unique_id; ?>" <?php if(isset($_POST['box']) && !empty($_POST['box']) && in_array($unique_id, $_POST['box'])) echo "checked='checked'"; ?>>
OR
<input type="checkbox" name="box[]" value="<?php echo $unique_id; ?>" <?php my_function(); ?>>
Excellent question and solutions! There seem to be relatively few examples that use an array method to preserve Post selections, and the one provided here is relevant and very helpful even years later.

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