testing for empty multi-select lists - php

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)

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

ZF2 validator : empty an object property in validation if form value is null

In a form, I have a multiple select, where the input can have 0 or X values.
Problem is, if user doesn't send value, in ajax, the variable is an empty array and it is not sent in the request : the object property is not set to null and it keeps its old value, and validation keeps ok.
The only trick I found is to send a variable [0], and in this case it works.
Do you have any idea how can I empty an object property in validation ?
Please read about Zend\Filter\Null: https://packages.zendframework.com/docs/latest/manual/en/modules/zend.filter.set.html#null
Per default this filter works like PHP‘s empty() method; in other words, if empty() returns a boolean TRUE, then a NULL value will be returned.
If you use this filter in your Input Filter for this field, it will return a null instead of an empty array.

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

Using POST data in array_diff with CakePHP

What I'm trying to do:
treat the POST data from a multi-select input with the array_diff() function
Initial code:
$relations_to_delete=array_diff($selectedEnjeuxMetiers,$this->request->data['EnjeuxMembership']['EnjeuxMetier']);
Probem: It was not working when nothing was selected in the multiselect input
Current solution:
if(!empty($this->request->data['EnjeuxMembership']['EnjeuxMetier'])){
$relations_to_delete=array_diff($selectedEnjeuxMetiers,$this->request->data['EnjeuxMembership']['EnjeuxMetier']);
}else{
$relations_to_delete=$selectedEnjeuxMetiers;
}
This solution works. !=null was not working, nor gettype()=="array"
Question: Could anyone could explain why the if(!empty()) test is necessary, and if the problem comes from the POST data or the array_diff function?
EDIT: It works with gettype()=="array". The problem was that the type when there is no data is not an empty array but an empty string.
Additional info: CakePHP docs about the way Post data are converted to an array.
With the function "empty()", the variable is considered empty if it is equal to:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
The value should be coming "" or NULL when no option is selected.
The problem was that the type when there is no data is not an empty array but an empty string.

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