Depending on the submission-mechanism of an HTML form, any checkbox element values may be seen as 'on', 'off', 1, 0, 'true', 'false'. For this problem an unchecked input field will be also be submitted (because that's what I want) and it may appear as 0 or no or false.
The purpose here is to convert scalar values that logically represent a boolean value to a boolean variable. Such as:
Is there a helper in the Laravel framework that can "cast" a submitted FormData checkbox (or a plain form) to a boolean?
I could roll my own, but asking here is worth a shot.
Here is what I would use:
<?php
function checkbox_boolean($parameter) {
if (is_bool($parameter)) return $parameter;
if (is_object($parameter)) return count(get_object_vars($parameter)) !== 0;
if (is_array($parameter)) return count($parameter) !== 0;
if (is_numeric($parameter)) { return (boolean) $parameter; }
$p = is_string($parameter) ? strtolower($parameter) : $parameter;
switch ($p) {
case 'yes';
case 'on';
case 'true';
return true;
break;
case null;
case 'no';
case 'off';
case 'false';
return false;
break;
}
return false;
}
These are the most common cases I would like to cover:
<?php
print_r([
'yes' => [
'"true"' => checkbox_boolean('true'),
'true' => checkbox_boolean(true),
'1' => checkbox_boolean(1),
'"1"' => checkbox_boolean('1'),
'yes' => checkbox_boolean('yes'),
'YEs' => checkbox_boolean('YEs'),
'<non-empty object>' => checkbox_boolean((object) [ 'z' => 'z']),
'<non-empty array[0]>' => checkbox_boolean([0]),
],
'no' => [
'"false"' => checkbox_boolean('false'),
'false' => checkbox_boolean(false),
'0' => checkbox_boolean(0),
'"0"' => checkbox_boolean('0'),
'no' => checkbox_boolean('no'),
'No' => checkbox_boolean('No'),
'<empty object>' => checkbox_boolean(new stdClass),
'<empty array []>' => checkbox_boolean([]),
]
]);
This question is not a duplicate of "How to convert strings to boolean" because this is not a generic problem.
I am asking about the specific process of converting HTML forms, or rather checkbox elements to a boolean. An important part of the question/problem is identifying the common values that these checkboxes generate when submitted by various (common) methods and parsed by PHP. In retrospect this does not make much sense because the value can be 100% arbitrary and set via the value= attribute of the input element.
According to this article, the canonical way would be something like the following and would return;
if (filter_has_var(INPUT_POST, 'agree')) {
$agree = filter_input(INPUT_POST, 'agree',
FILTER_VALIDATE_BOOLEAN,
[FILTER_NULL_ON_FAILURE]);
if (! is_null($agree)) {
...
}
}
Resources:
The checkbox_boolean($parameter) function in the question is good enough. You can even get it with composer.