Reputation: 449
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';
}
Upvotes: 0
Views: 94
Reputation: 48357
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';
}
Upvotes: 0
Reputation: 8050
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.
Upvotes: 2
Reputation: 46602
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';
Upvotes: 0
Reputation: 1324
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:
}
Upvotes: 1