I am building something which uses a form element with '#type' => 'checkboxes'
.
I want this to be reusable, so it should accept anything as option values that works as a PHP array key (integers and non-integer strings).
$form['checkboxes'] = [
'#type' => 'checkboxes',
'#options' => [
0 => 'zero',
'' => 'empty string',
' ' => 'space',
'other' => 'Other',
],
];
However there seems to be a problem with values 0
(zero) and ''
(empty string).
Even when the checkboxes for '' or 0 are checked, the values are gone in the $element['#value']
array, e.g. when checking with a custom '#element_validate' callback.
$element['#value'] === [
# '' and 0 are gone, even if they were checked.
' ' => ' ',
'other' => 'other',
];
Interestingly, the $_POST
still contains the values, with an interesting twist, where space and empty string behave like array insertion via []
. I suppose this is due to the way POST data is sent.
$_POST['checkboxes'] === [
0 => '0',
1 => '',
2 => ' ',
'other' => 'other',
];
I can imagine why all of this happens, but is there a workaround or solution?
EDIT: The previous version of the code snippet was misleading, sorry. I had mixed up $_POST and the original '#options' array.
0 => 0,
'_'
) to it when creating the form elements and remove that prefix in the submit handler. Thus, a key like0
would become'_0'
,''
becomes'_'
,' '
becomes'_ '
, and so on.