Checkbox Group Function and Usage In CodeIgniter, I have created function (helper) to populate, store and retrieve checkbox group. I just wonder if I have written code is in proper way and optimized or needs some more finishing?

Function

if ( ! function_exists('checkbox_group') )
{
    function checkbox_group($checkboxes = array(), $name)
    {

    // setting hidden field for null, if no checkbox selected
    echo form_hidden($name.'[]', 'null');

    // start checkbox loop
    foreach($checkboxes as $check =&gt; $label_text):

        $checked = FALSE;                   
        $selects = get_config_row($name);
        if(in_array($check, $selects))
        $checked = TRUE;

        echo '&lt;div class="checkbox"&gt;';
        echo form_label(form_checkbox($name.'[]', $check, $checked, 'id="'.$check.'" class="checkbox"') . $label_text, $check);
        echo '&lt;/div&gt;';
    endforeach;
    }
}


Usage

// checkbox items
$checkboxes = array(
    'noindex'=&gt;'No Index',
    'nofollow'=&gt;'No Follow',
    'noarchive'=&gt;'No Archive',
    'nosnippet'=&gt;'No Snippet'
);

// render checkboxes useing function
checkbox_group($checkboxes, 'indexes');
I haven't worked with CodeIgniter before, so if I say something that argues their standards, please excuse me.

It's such a basic piece of code that there isn't too much to be said. One things I notice right off the bat, your checkbox_group() function has a first parameter with a default value. I'm surprised you haven't done anything about this because it should be throwing you a warning.


  Note that when using default arguments, any defaults should be on the
  right side of any non-default arguments; otherwise, things will not
  work as expected.


As per the PHP Functions page

To better separate the function's business and the view, consider creating an output string and returning it to be echoed. You'd then have:

$output = '';
// setting hidden field for null, if no checkbox selected
$output .= form_hidden($name . '[]', 'null');

// start checkbox loop
foreach ($checkboxes as $check =&gt; $label_text) :

    $checked = FALSE;
    $selects = get_config_row($name);
    if (in_array($check, $selects))
        $checked = TRUE;

    $output .= '&lt;div class="checkbox"&gt;';
    $output .= form_label(form_checkbox($name . '[]', $check, $checked, 'id="' . $check . '" class="checkbox"') . $label_text, $check);
    $output .= '&lt;/div&gt;';
endforeach;
return $output;


Now you call:

// render checkboxes useing function
echo checkbox_group($checkboxes, 'indexes');