Plugin settings page checkbox not saving – one options array with sub array

I finally got this one. I’ll write out the solution for any other inexperienced person, like me, who is trying to handle a checkbox array when using just one options array.

First, the two articles I linked two at the top of the question are good for learning the basic about the topic.

Solution – part one:

I am using an options array, with all the possible options, and a values array to hold just the items that are checked. I was creating the values array incorrectly. Rather than being an associative array, it needs to be just a “regular array” holding just the keys from the options array.

So, in my setup, instead of setting ‘activities’ in the default settings to

 array (
            'baseball'  => '',
            'golf'      => '',
            'hockey'    => ''
        ), 

I want just

   array ()  

Solution – part two

If no checkboxes are chosen, when the settings are saved the $values array becomes NULL. But I need to use functions that require an array to make my tests for validation and for evaluating the checkboxes. So I need to make sure $values is always an array. So I need

    if (is_null($data['activity'])) {
    $data['activity'] = array();
}

Solution – part 3

My checked() function was wrong. Once I had fixed my array as discussed above, I am searching if the current $key from the $options array is a value from the $values array.

$checked = checked((in_array($key, $values)), true, false);

Solution – part 4

Since ‘activities’ is a sub array of the option values, I need to set the name variable in the checkbox statements to reflect that.

So I use

name="%1$s[%2$s][]"

which generates

name="rpq_plugin_option_name[activity][]"

Now my checkboxes update and save.

tech