Bad code or not?



  • <?php
    if (isset($post['attachment']['photo']['src_xxbig'])) {
        $img = $post['attachment']['photo']['src_xxbig'];
    } else
        if (isset($post['attachment']['photo']['src_xbig'])) {
            $img = $post['attachment']['photo']['src_xbig'];
        } else
            if (isset($post['attachment']['photo']['src_big'])) {
                $img = $post['attachment']['photo']['src_big'];
            } else
                $img = false;
    ?>
    

    Is there any way to lower the code?



  • One fragment can be written so:

    $photo = $post['attachment']['photo'];
    if (isset($photo['src_xxbig'])) {
        $img = $photo['src_xxbig'];
    } else if (isset($photo['src_xbig'])) {
        $img = $photo['src_xbig'];
    } else if (isset($photo['src_big'])) {
        $img = $photo['src_big'];
    } else $img = false;
    

    If this logic is repeated several times, you can take it as a function:

    $img = fallback(
        $post['attachment']['photo'],
        ['src_xxbig','src_xbig','src_big'],
        false
    );
    

    function fallback( $src, $keys, $default) {
    foreach( $keys as $key) {
    if( array_key_exists( $src[$key]) return $src[ $key];
    }
    return $default;
    }

    The first option was used isset()And in the second, array_key_exists() Because in private 1, it's clear that there's no expectation. NULL♪ As a more universal decision, it would be better to envisage such an option. The difference is, $arr[$key] = NULL (NULL key element value) isset() return FALSE as if there's no such key. array_key_exists() - TRUE, as it is, because the key is defined.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2