changing boolean values in php - php

I have a bunch of values from checkboxes that are boolean. Al I want to do is set them to yes if they are 1 and no if they are 0.
My code fails, looks ok to me?
$item = $form_state['values']['item1'] == 1 ? 'Yes' : 'No';

If your checkboxes have value attribute equal to 1, it should be OK:
<input ... type="checkbox" value="1" />
If you have not set these values or in all the cases you may just check, if they exists in $_GET or $_POST array (assuming $form_state is taken from there):
$item = isset($form_state['values']['item1']) ? 'Yes' : 'No';
The above example, should works for you. Keep in mind radio buttons and check boxes will not be set in $_GET or $_POST if they are not selected, at all, which also may generate Notice or Warning, if trying to access non-existing index.
In older versions of php you might need to use $_REQUEST.

Related

Why do false statements print nothing rather than 0 in PHP?

Here's a simple example:
echo 3==3; // echoes 1
echo 3==2; // should echo 0, yet echoes nothing
I noticed this as I was designing a form which entails a checkbox. When ticked, the checkbox passes a value of 1, when unticked, rather than passing a value of 0 as one would expect, it passes nothing; an undefined boolean so to speak.
I tried solving this with the following code:
$myBool = isset($_POST['myCheckbox']);
However, this doesn't seem to work either.
One solution to passing the checkbox value to $myBool would be to do some if-else conditioning, but I want a more concise solution. Is this possible?
In PHP, every decision makes statement returns a boolean value, either true or false. So, echo 3==3; is a true statement, That's why it returns 1 and echo 3==2; is a false statement, that's why it returns nothing.
But if you want to echo out the associated integer of false (which is 0), then you can use typecasting. Like:
echo (int)(3 == 2);
It will print out 0.
Test Code
// http://php.net/manual/en/language.operators.comparison.php
echo 3==3;
echo "<br>---------------<br>";
echo 3==2;
echo "<br>---------------<br>";
var_dump(3==3);
echo "<br>---------------<br>";
var_dump(3==2);
Output
1
---------------
---------------
boolean true
---------------
boolean false
The reason is for no output is you are trying to echo the boolean "false", which prints nothing.
The statement 3 == 2 evaluates to false, and as noted in the PHP documentation for echo under the examples section, running echo false won't print anything because it's not technically a function. However, you can use var_dump instead.
echo 3 == 2; // no output
echo false; // no output
var_dump(3 == 2); // outputs bool(false)
var_dump(false); // outputs bool(false)
The actual reason for your question about why a statement that evaluates to echo false; prints an empty string, is given in the documentation on strings, in the section about casting to string:
Converting to string
A value can be converted to a string using the (string) cast or the
strval() function. String conversion is automatically done in the
scope of an expression where a string is needed. This happens when
using the echo or print functions, or when a variable is compared to a
string. The sections on Types and Type Juggling will make the
following clearer. See also the settype() function.
A boolean TRUE value is converted to the string "1". Boolean FALSE
is converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.
The reason that you can't test an unchecked checkbox, the way you tried, is that browsers don't send unchecked checkbox states on form submissions.
Typical solutions to this conundrum are:
Keep track of all available checkboxes in the backend and compare them upon receiving a form submission.
Add a hidden field in your HTML form before the actual checkbox, giving it the same name as the checkbox and a value that represents the unchecked state.
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1">
These hidden fields will be submitted upon form submission and will be overwritten by the checkbox value if it is checked1.
1) The values will actually both be send if the checkbox is checked, but PHP will overwrite any earlier received value with a later received value if they have the same parameter name (unless the parameter name represents an array without explicit key names, like name="checkbox[]" instead of name="checkbox[1]").

Regex to validate checkbox input

I'm having some issues with codeigniter's validation filter when using checkboxes. I typically used the numeric filter for checkboxes, presuming it would filter for 0 or 1 but now I see there are several instances in which this fails.
Does anyone know a regex that I can put in the preg_match to validate a checkbox?
I would like this to allow for booleans and a few others 1, 0, null, true, false, empty etc...
A checkbox only returns one value. It's value (as indicated in its value= attribute) or 'true'. If the checkbox is not selected, it is not passed in the POST request. Therefore, for validation, you only need to check for 2 things:
Was it even selected in the first place?
Is its value consistent with what you expect it to be?
So:
if (isset($_POST['checkbox']) && ($_POST['checkbox'] == 'true') { //or whatever value you want
Should do the trick nicely. Unless I've misunderstood your question in which case please comment.
Checkboxes either have a value or they don't. If they have a value they're checked, if they don't then they're not checked.
A regex would be serious overkill here, you only need to check if the checkbox exists in the submitted data.
$checkBoxChecked = isset ($_POST['checkbox_name_goes_here']);

PHP $_REQUEST $_GET or $_POST

Say I have a form:
<form action="form.php?redirect=false" method="post">
<input type="hidden" name="redirect" value="true" />
<input type="submit" />
</form>
On form.php:
var_dump($_GET['redirect']) // false
var_dump($_POST['redirect']) // true
var_dump($_REQUEST['redirect']) // true
How do I get the injected query string parameter to override the $_POST value so $_REQUEST['redirect'] will = false ?
If you want to change precedence of $_GET over $_POST in the $_REQUEST array, change the request_order directive in php.ini.
The default value is:
request_order = "GP"
P stands for POST and G stands for GET, and the later values have precedence, so in this configuration, a value in the query string will override a value passed by POST in the $_REQUEST array. If you want POST to override GET values, just switch them around like so:
request_order = "PG"
You'll need to restart the webserver/php for that to take effect.
(Edited to use the more appropriate request_order as Brad suggested, rather than variables_order)
See the request_order directive in PHP.ini.
Really though, you should be explicitly using the superglobal that you specifically want. Otherwise, you cannot rely on consistent behavior from system to system, and then your variables can be accidentally overwritten.
See the request order parameter of PHP. Here you can set whether the array fills post, get, cookie or any combo thereof.
$_REQUEST['redirect'] = $_POST['redirect'];
or
$_REQUEST['redirect'] = $_GET['redirect'];
depending on what you want
If you meant false at that last line there, and want $_REQUEST to still have data from both POST and GET data, and don't want to mess with the config, use this:
$_REQUEST = array_merge($_POST, $_GET);
I just wanted to add in #Chris Hepner 's answer, that as he said:
"the later values have precedence",
later being the letter P than G, and so it means that the POST values have precedence and that POST values overwrite the GET values.
A code example:
<?php
echo ini_get('request_order')."\n";
echo ini_get('variables_order')."\n";
echo var_export($_REQUEST,1);
?>
Results in:
EGPCS
array (
'abc' => '5',
'fed' => '2',
'cde' => '8',
...
)
I added this comment for others looking for information on this

Codeigniter unchecked checkbox value = blank?

I have this database where I have to capture a lot of yes/no questions, and the prefered method for the users is checkboxes. Everything is working as it should, except when it comes to retreive and show the values. Unchecked boxes return values of "0"
Is there anyway to either ignore and not display "0" in the reports OR change the default value from "0" to blank"
result = $this->input->post('checkbox',TRUE)==null ? 0 : 1
this is nothing to do with CodeIgniter. :)
How about this?
if($_POST['checkbox']==0)
$_POST['checkbox'] = '';
It is returning 0 because that is false and that's what check boxes returned when not checked. Just add an if in your CI processing method that returns whatever value you want if the checkbox value==0.
Edit: Just to clarify, this doesn't have anything to do with your CI. What I mean by it is returning 0 is that that is what the form itself is returning - that the behavior of a checkbox. To change the value will take a quick check in your CI code to change the 0 to a value you want. I assume you are accessing the value somewhere to create your email.
since the the checkbox returning null value while unchecked, you won't get a value while posting. Here is a simple quick solution for returning unchecked value from checkbox,
<input type="hidden" name="cbox" value="0" />
<input type="checkbox" name="cbox" value="1" />
if( ! $_POST['checkbox']) $_POST['checkbox'] = '';
If a checkbox is not checked, no data is sent for it. (If it is checked, the value attribute is sent). Attempting to read $_POST['checkbox'] will cause a PHP error (unless you use empty() or isset(), which are special language constructs).
this->input->post('checkbox') will return FALSE if the checkbox data is not set, i.e. if it was not checked. There's no way to change that value, I'm afraid. If you want a different value, you will need to manually compare FALSE and use a different value.
Finally, when you submit FALSE to the database using CodeIgniter's DB access API, it is converted to '0'. This would work well for a boolean column in the database. When you read out a boolean column, you'll get whatever your database's preferred code for TRUE is, regardless of what you submitted originally. (With the possible exception of sqlite, which is weakly-typed, a bit like PHP is).

php checkboxes always showing checked

I've got a single checkbox which i'd like the unchecked value to be 0 and the checked value to be 1, but when the post goes through, it always shows as 1 whether the box is checked or not..
Here's the checkbox:
<input name="stock[]" type="checkbox" id="stock[]"> value="1" />
here's what it spits out regardless of whether it's checked or not.. (there are multiple "stock" checkboxes..
[stock] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
I can't seem to get it working.. :S Any ideas? :)
It seems like you have a extra > in your Checkbox HTML. Value is not used in case of checkboxes.
<input name="stock[]" type="checkbox" />
because you have value="1", the form will always submit the value regardless of whether checked or not. So remove the value attribute will help.
And to preset the checkbox to be checked, use the checked attribute instead. Example:
<input name="stock[]" type="checkbox" checked="checked" />
(Obviously, you need to start by removing that extraneous > sign.)
Checkboxes and radio buttons must have a value attribute. If they're checked, that value is sent when the form is submitted; if they're not checked, no value is submitted. Thus, you can't directly do the "0 if unchecked, 1 if checked" thing. What you can do instead is use the value attribute to detect which checkboxes were checked.
<input type="checkbox" name="stock[]" value="1" id="stock1" />
<input type="checkbox" name="stock[]" value="2" id="stock2" />
<input type="checkbox" name="stock[]" value="3" id="stock3" />
If the 1st and 3rd boxes are checked, but the 2nd is not, then when you look at the value of the stock[] array in your code, you'll find that it contains 1 and 3, but not 2.
Edit: I just confirmed that the reason it looked like all of your checkboxes had values submitted was that you failed to give the form any way to differentiate among them. If you have multiple checkboxes with not only the same name but the same value, then your form results will look something like "stock[] = 1, stock[] = 1, stock[] = 1". PHP will then interpret this as stock[1] = 1, stock[2] = 1, etc., but the point is that stock[2] might actually be the fourth checkbox - neither the form nor php has any way to tell where each value came from.
So bottomline is, you can either use the same name for a series of checkboxes, OR you can use the same value, but not both at once: if you use the same name, you have to use the value to differentiate among the controls; and vice versa, if you want to use the same value, you need to use different names.
By the way, if you don't specify the value of a checkbox, then most browsers will supply a default value of their own - for example, IE and Firefox use "on" (or "ON" in some versions). But depending on such defaults is always a bad idea.
I'm not sure you can/should name an input element "stock[]" - try getting rid of the [] and re-test.

Categories