2011-02-12 202 views
1
<?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?> 

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

基本上,我想擺脫管道,如果box2是空的。有沒有更好的方法來寫這個?有沒有更優雅的方式來編寫這段代碼?

+2

優雅PHP ...哈哈。 – 2011-02-12 04:18:02

回答

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

謝謝。只是一個側面的問題。 ($ box2)旁邊的問號是什麼? – J82 2011-02-12 04:16:52

0

很難說什麼是「最好」的方式將其優雅的書寫,而無需一個事物的宏大計劃,但至少可以縮短如下:

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

另外,如果你不喜歡&&風格,你可以使用一個三元操作符:

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

或者另一個條件。

粗磨,如「最」優雅的方式將沿行採取什麼$box1$box2代表定睛一看,然後創建一個視圖助手(MVC中的方法):

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

只使用ternary operators

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