简体   繁体   English

检查多个条件或 PHP

[英]Check multiple conditions OR PHP

Is there any more elegant way to write an IF with multiple OR conditions?有没有更优雅的方法来编写具有多个 OR 条件的 IF? 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';
}

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.添加break是为了防止多次执行 if 语句,但不是严格必要的。

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:
}

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';
}

Imo, make a has() function or similar which you can reuse, it then doesnt matter how long the lines are you have abstracted it. Imo,制作一个可以重用的has()函数或类似的函数,那么你抽象它的行有多长并不重要。 It would be equivalent to some (ie some values in the array should be true).它相当于some (即数组中的某些值应该为真)。

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM