Dynamically write the "checked" attribute on only one of several radio buttons

81 views Asked by At

What's a good way to reduce or simplify the following php function to check the applicable input field?

  <?php

  $options = get_option( 'navbar_style', '' );
  
  $right = $left = $fade = '';

  if( isset( $options['style'] ) ) {
    if( $options['style'] == 'right' ) {
      $right = ' checked="checked"';
    }
    if( $options['style'] == 'left' ) {
      $left = ' checked="checked"';
    }
    if( $options['style'] == 'fade' ) {
      $fade = ' checked="checked"';
    }
  }

  ?>

  <label><input type='radio' name='navbar_style[style]' value='right' <?php echo $right; ?> >Right <em>(Default)</em></label>
  <label><input type='radio' name='navbar_style[style]' value='left' <?php echo $left; ?> >Left</label>
  <label><input type='radio' name='navbar_style[style]' value='fade' <?php echo $fade; ?> >Fade</label>
5

There are 5 answers

0
mickmackusa On BEST ANSWER

As a programmer, you should keep an eye out for repeating patterns in your code. Clearly there is duplicate HTML markup with minimal textual adjustments. The acronym D.R.Y. means "Don't Repeat Yourself".

Create an array of those dynamic data points then implement a loop to generate the desired markup. This will help to prevent typos and make your script much easier to maintain.

Code: (Demo)

$options = ['style' => 'left'];
  
$radios = [
    'right' => 'Right <em>(Default)</em>',
    'left' => 'Left',
    'fade' => 'Fade',
];

foreach ($radios as $value => $text) {
    printf(
        "<label><input type='radio' name='navbar_style[style]' value='%s'%s>%s</label>\n",
        $value,
        ($options['style'] ?? '') === $value ? ' checked' : '',
        $text
    );
}
0
Markus Zeller On

You can use dynamic variable setting, but not recommended! See next example for proper use.

$options['style'] = 'left';
$right = $left = $fade = '';

if (in_array($options['style'] ?? '', ['right', 'left', 'fade'])) {
    ${$options['style']} = ' checked="checked"';
}

var_dump($right, $left, $fade);
string(0) ""
string(18) " checked="checked""
string(0) ""

A much cleaner way would be this version and use for example $checks['left'] instead of $left.

$checks = [];
foreach (['right', 'left', 'checked'] as $check) {
    $checks[$check] = $options['style'] === $check ? ' checked="checked"' : '';
}

var_dump($checks);
array(3) {
  'right' =>
  string(0) ""
  'left' =>
  string(18) " checked="checked""
  'checked' =>
  string(0) ""
}
0
Alon Alush On

You can try this:

$options = get_option( 'navbar_style', '' );
$styles = array('right', 'left', 'fade');

$checked = array_fill_keys($styles, '');
if(isset($options['style']) && in_array($options['style'], $styles)) {
  $checked[$options['style']] = 'checked="checked"';
}
0
Lagaart On

You may also do it like this:

$style = ['right' => '', 'left' => '', 'fade' => ''];
    
if (isset($options['style']) && array_key_exists($options['style'], $style)) {
    $style[$options['style']] = ' checked="checked"';
}
0
Nigel Ren On

Perhaps more compact to create a function and pass in the options, then it's just a test to see if that option is set and return the corresponding html...

  function styleCheck($option, $options)
  {
      return ($options['style'] ?? '') == $option ? ' checked="checked"' : '';
  }
  ?>

  <label><input type='radio' name='navbar_style[style]' value='right'<?php echo styleCheck('right', $options); ?>>Right <em>(Default)</em></label>
  <label><input type='radio' name='navbar_style[style]' value='left'<?php echo styleCheck('left', $options); ?>>Left</label>
  <label><input type='radio' name='navbar_style[style]' value='fade'<?php echo styleCheck('fade', $options); ?>>Fade</label>