Pages

Handle PHP multiple choice select dropdown and checkbox

This took me hours to figure out that something was wrong in the PHP.

is_array() and count() can't really distinguish array() or string, if there is only one element.

For example.

$test = array('123');
is_array($test) will return true;
count($test) return 1

$test = '123';
is_array($test) will still return true.
count($test) will still return 1.


So there is no point to check a submitted field from PHP form as an array or a string.

This will cause problem when handling multiple choice select dropdown box or checkbox.

In PHP multiple choice field will need to be name with [] after the field.

For example:

state_id[]
In normal case, if the select box only accept one selection, the field name will be just state_id.

This confuse the PHP form validation. It returns just one string. So you will get error message when handling it with foreach loop.

for example
foreach($_POST['state_id'] as $state_id)
You will get an error like this.

Severity: Warning

Message: Invalid argument supplied for foreach()

Solutions:

No matter the select dropdown box allows to choice one or multiple options, always use multiple format. In other words, always use [] after the field name in the html form.

It will work with the validation process and treat the field as array as always.

No comments:

Post a Comment

Thank you for your feedback. If you find the tip and trick useful, feel free to share with your friends on Facebook, Twitter and G+!