phpif-statementradio-buttonwordpress-themingchecked

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


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>

Solution

  • 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
        );
    }