Dealing with checkboxes quickly

I've been working with the Forms API for some time. I've found a very useful shorthand for that today.

Normall, when a form is submitted, the resulting checkboxes entry in form_state['values'] is an associative array, in which they key is the name of the checkbox, and the value is either 0 (not checked) or the key (checked).

Until now, to filter out the unchecked values I used to do something like 

[..]
$checkboxes = $form_state['values']['checkboxes'];
$checkboxes = array_flip($checkboxes);
unset($checkboxes[0]);

... which is not very pretty. What I found while reading the source for the flag module was a much better way:

[..]
$checkboxes = $form_state['values']['checkboxes'];
$checkboxes = array_values(array_filter($checkboxes));

This exploits the behavior of array_filter() when the second value is null -- it simply strips the elements that have a value that evaluates to false. The additional call to array_values() is not really necessary unless you want numeric keys.

In any case, I hope this helps someone else do things in a simpler way :)

Image from here