skip to Main Content

Is there any more elegant way to write an IF with multiple OR conditions? Currently, my code is like below, but it doesn’t look interesting like that.

if ( has_block( 'cgb/block-imoney-blocks' ) || has_block( 'cgb/block-idh-affiliates' ) || has_block( 'cgb/block-idh-best-summary') || has_block('cgb/block-idh-highlights')) {
    echo 'Value Found';
}

4

Answers


  1. If it is a lot of blocks it’s more readable to iterate through an array like this:

    <?php
    $blocks = ['cgb/block-imoney-blocks', 'cgb/block-idh-affiliates', 'cgb/block-idh-best-summary', 'cgb/block-idh-highlights'];
    
    foreach ($blocks as $block) {
        if (has_block($block)) {
            echo 'Value Found';
            break;
        }
    }
    

    The break is added to prevent multiple times execution of the if-statement but not strictly nessecary.

    Login or Signup to reply.
  2. With better formatting?

    if ( has_block( 'cgb/block-imoney-blocks' ) 
      || has_block( 'cgb/block-idh-affiliates' ) 
      || has_block( 'cgb/block-idh-best-summary') 
      || has_block( 'cgb/block-idh-highlights')
      ) {
        echo 'Value Found';
    }
    
    Login or Signup to reply.
  3. you could put the conditions in a function and pass the values in an array.

    $blocks_array = array(
         'cgb/block-imoney-blocks',
         'cgb/block-idh-affiliates',
         'cgb/block-idh-best-summary',
         'cgb/block-idh-highlights'
    );
    
    if(contains_block($block_array)){
        echo 'Value Found';
    }
    
    function contains_block($block_array){
        foreach ($block_array => $block){
            if (has_block($block)){
                return true;
             }
        }
        return false:
    }
    
    Login or Signup to reply.
  4. Imo, make a has() function or similar which you can reuse, it then doesnt matter how long the lines are you have abstracted it. It would be equivalent to some (i.e some values in the array should be true).

    function has($blocks) {
        return array_reduce($blocks, fn($acc, $cur) => $acc || has_block($cur), false);
    }
    
    if (has([
      'cgb/block-imoney-blocks', 
      'cgb/block-idh-affiliates', 
      'cgb/block-idh-affiliates'
    ])) echo 'Value Found';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search