开发者

Is there a more elegant way to write this code?

<?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?>

<?php if (!empty($box1) && empty($box2)) { echo 'content here'; } ?>

Basically, I want to get rid of the pipe if box2 is empty. Is there a better way to write t开发者_运维问答his?


<?php if (!empty($box1)) { echo (empty($box2) ? '' : ' | ') . 'content here'; } ?>


It's hard to say what's the "best" way to write it elegantly without having a grander scheme of things, but at least you can shorten it as follows:

<?php if(!empty($box1)) { echo (!empty($box2) && ' |') . 'content here'; } ?>

Alternately, if you don't like the && style, you can use a ternary operator:

<?php if(!empty($box1)) { echo (!empty($box2) ? ' |' : '') . 'content here'; } ?>

Or another conditional.

Coarsely, if "most" elegant way would be to take a closer look at what $box1 and $box2 represent and then create a view helper (in the MVC methodology) along the lines of:

class SomeModel {
  int $box1;
  int $box2;
  function make_suffix() {
    $suffix = '';
    if(!empty($this->box1)) {
      if(!empty($this->box2)) {
        $suffix .= ' | ';
      }
      $suffix .= 'content here'; 
    }
    return $suffix;
  }
}


<?php
if (!empty(&box1)) {
  if (!empty($box2) {
    echo ' | ';
  }
  echo 'content here';
}
?>


Using just ternary operators:

<?php echo !empty($box1) ? ( !empty($box2) ? ' | ' : '' ) . 'content here' : '' ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜