Trouble with checked() for array of multiple checkboxes

I can't get the checked() to return what I expect.

Data:

Options:  = array (
'baseball' = 'Baseball',
'golf' = 'Golf',
'hockey' = 'Hockey',
)

Values:  = array (
'baseball' = 'Baseball',
'golf' = '',
'hockey' = '',
)

I'm using this code to try to return 'checked="checked"'

foreach ( $options as $key = $title ) {
    rpq_plugin_debug_var( $key, 'Key: ' );
    rpq_plugin_debug_var( $title, 'Title: ' );
    $checked = checked((in_array($key, $values)), true, false);

I'd expect the baseball option to return 'checked="checked"' but it returns ''.

I've also tried this, which actually makes more sense to me, with no success, either.

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

Where is my error?

Many thanks.

EDIT: See comments below this post for answer.

  1. Make $values array not associative.

       Values:  = array (
    'baseball',
    'golf'
    
    )
    
  2. Use this line to identify checkmarks

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

Topic array php forms Wordpress

Category Web


Why take empty answer

foreach ( $options as $key => $title ) {
      rpq_plugin_debug_var( $key, 'Key: ' );
      rpq_plugin_debug_var( $title, 'Title: ' );
      $checked = checked((in_array($title, $values)), true, false);

After this loop end you get empty $checked because it replace every loop step.

Trace:

1: $checked = 'checked="checked"'
2: $checked = '';
3: $checked = '';

After loop $checked = '';

So need return array for answers for multiply array like: $checked[$key] = checked((in_array($title, $values)), true, false);

So you got answer:

$checked = array (
'baseball' => 'checked="checked"',
'golf' => '',
'hockey' => '',
)

And then use where it need.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.