写if else语句的方法更短?

时间:2012-12-08 09:08:07

标签: php if-statement

<?php
  $typeface = $page->typeface();
    if($typeface == '') {
  } else {
      echo '<li><span>Typeface: </span>'.$typeface.'</li>';
  }
?>


我最初尝试过下面的PHP代码,但它仍会输出HTML:
<li><span>Typeface: </span></li>即使字符串为空。


<?php $typeface =  $page->typeface(); 
  if (!empty($typeface)): ?>
    <li><span>Typeface: </span><?php echo $typeface ?></li> 
  <?php endif; ?>


所以我的问题是,如何以更短的方式在最顶端编写代码?

5 个答案:

答案 0 :(得分:3)

$typeface = trim($page->typeface());
if($typeface != '')
    echo '<li><span>Typeface: </span>'.$typeface.'</li>';

编辑:(删除新行)

$typeface = trim(str_replace(array("\r", "\r\n", "\n"), '', $page->typeface()));
if($typeface != '')
    echo '<li><span>Typeface: </span>'.$typeface.'</li>';

答案 1 :(得分:2)

试试这个

(isset($typeface) && !empty($typeface))?echo "<li><span>Typeface: </span>".$typeface."</li>":"";

答案 2 :(得分:0)

($typeface=="")?echo "":echo '<li><span>Typeface: </span>'.$typeface.'</li>';

答案 3 :(得分:0)

根据$page->typeface()方法的返回类型以及代码的位置(看起来像是在模板视图中),我可能会选择:

<?php if ($typeface === $page->typeface()): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

PHP docs here:

Alternative syntax for control structures

See here了解使用<?=...?>短标记时应注意的注意事项。

<?=...?>的替代方案是:<?php echo $typeface; ?>

希望有所帮助!


编辑:

实际上,我早先猜到了自己(我责怪睡眠剥夺)。我最初有这个代码(trim()除外):

<?php if ($typeface = trim($page->typeface())): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

我在$typeface中设置变量if()。这种技术应该可以缩短你的代码。

以下是使用简单字符串的工作示例:

<?php $foo = ""; ?>
...
<?php if ($typeface = trim($foo)): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

...输出:没什么。

<?php $foo = 'I\'m a string!'; ?>
...
<?php if ($typeface = trim($foo)): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

...输出:<li><span>Typeface: </span>I'm a string!</li>(显然,错过了开始和结束<ul></ul>

答案 4 :(得分:0)

试试这个..

$typeface = $page->typeface();
echo $res=($typeface != '')?'<li><span>Typeface: </span>'.$typeface.'</li>':'';