Wednesday, March 21, 2018

php - Converting a checkbox to a boolean

Depending on the submission-mechanism of an HTML form, any checkbox element values may be seen as 'on', 'off', 1, 0, 'true', 'false'.



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:






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;
}

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'),
'' => checkbox_boolean((object) [ 'z' => 'z']),
'' => 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'),
'' => checkbox_boolean(new stdClass),
'' => 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 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.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...