Why do false statements print nothing rather than 0 in PHP? - 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]").

Related

testing for empty multi-select lists

multi-select lists are named thusly: <select name="list[]" multiple>
When the form is submitted, if the user hasn't selected anything, then I wish to ignore that input.
I'm trying:
if (isset($_POST["list"]))
and
if (count($_POST["list"]))
but that throws an error, presumably because PHP doesn't receive the array unless at least one item is selected. If the user does select at least one of the options, there is no error.
The complaint is that "list" is a nonexistent index.
I need at least one of these solutions:
To force the submit to send an empty array so the index in $_POST will be legal, OR
I need to test for the existence of the index variable without throwing an error.
I'm also trying to use the try-catch syntax but having issues with that as well. I have a separate post open for that issue.
any suggestions on detecting a listbox with nothing selected?
Thanks,
Dana
Try using empty():
if (!empty($_POST["list"])) {
For your case, !empty() would be TRUE if list[] is set and if it has at least one value.
From the documentation:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Unit testing - how many test cases here

I have a method that takes an array as an argument, and returns true or false depending on the presence of a particular value.
In this scenario how many test cases should be written?
I think 3:
If the value is present
If the value is not present
If the array is empty (could be covered by 2 though?? )
I can think of 3 test cases:
If the array is not empty (or not null)
If the value is valid or not (I can pass an object where it expects a string :) )
If the value is present in array
It is the code of the function you want to test, so you cannot tell how many test cases are useful. Think again what your code does, how will the value be found?
An example: If your code tries to find a value with a certain name, and you make a string comparison, then think of the problems that can arise with string comparisons -> should the key be found case (in)sensitive, is null equal to an empty string, how does it handle duplicates and are other types converted correctly to strings (type juggling)?

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

changing boolean values in 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.

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).

Categories