简体   繁体   中英

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 this?

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

仅使用三元运算符

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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