变量中的if if / else PHP?

时间:2012-09-04 09:18:44

标签: php variables

你在变量中有一些代码,在Ben Rowe的一些帮助下我意识到我需要整理我的字符串,现在我似乎无法解决以下问题...包括if和else变量。我有以下代码,IF / ELSE不工作,如果有人可以提供帮助,那将非常感激。

 <?php if (!$logged) { ?>
<div id="payment-address">
  <div class="checkout-heading"><span>'.$text_checkout_account.'</span></div>
  <div class="checkout-content"></div>
</div>
<?php } else { ?>
<div id="payment-address">
  <div class="checkout-heading"><span>'.$text_checkout_payment_address.'</span></div>
  <div class="checkout-content"></div>
</div>
<?php } ?>
<?php if ($shipping_required) { ?>
<div id="shipping-address">
  <div class="checkout-heading">'.$text_checkout_shipping_address.'</div>
  <div class="checkout-content"></div>
</div>
<div id="shipping-method">
  <div class="checkout-heading">'.$text_checkout_shipping_method.'</div>
  <div class="checkout-content"></div>
</div>
<?php } ?>
<div id="payment-method">
  <div class="checkout-heading">'.$text_checkout_payment_method.'</div>
  <div class="checkout-content"></div>
</div>

<div id="confirm">
  <div class="checkout-heading">'.$text_checkout_confirm.'</div>
  <div class="checkout-content"></div>
</div>

我试过strippimg出PHP代码没有效果,我也尝试在下面的代码之前关闭php然后再次打开它但仍然没有结果:(

5 个答案:

答案 0 :(得分:2)

像这样使用它 -

<div class="checkout-heading"><span><?php echo $text_checkout_account ?></span></div>

或html + php

<?php

echo  '<div class="checkout-heading"><span>'.$text_checkout_account.'</span></div>';

答案 1 :(得分:2)

你不能在标签之外使用php变量。如果你需要一个变量,你必须使用php标签,并回显该值。这样做:

<?php if (!$logged) { ?>
    <div id="payment-address">
    <div class="checkout-heading"><span><?php echo $text_checkout_account ?></span></div>
    <div class="checkout-content"></div>
    </div>
<?php } else { ?>
    <div id="payment-address">
    <div class="checkout-heading"><span><?php echo $text_checkout_payment_address ?></span></div>
    <div class="checkout-content"></div>
    </div>
<?php } ?>

答案 2 :(得分:0)

如果要将PHP变量的内容放在HTML中,则必须使用:

<div class="checkout-heading"><span><?php echo $text_checkout_account; ?></span></div>

你也可以用以下方式做到:

<div class="checkout-heading"><span><?=$text_checkout_account; ?></span></div>

重要提示:第​​二个示例需要激活短标签。由于PHP 5.4.0默认情况下可用。

参考:http://www.php.net/manual/en/ini.core.php#ini.short-open-tag

答案 3 :(得分:0)

在HTML中这样做

<div id="payment-address">
  <div class="checkout-heading">
    <span>
      <?php echo $logged ? $text_checkout_payment_address : $text_checkout_account?>
    </span>
  </div>
  <div class="checkout-content"></div>
</div>

如果您对echo感到困惑,请阅读Ternary operator

答案 4 :(得分:0)

您可以尝试三元运算符,如下所示:

<div id="payment-address">
   <div class="checkout-heading"><span><? echo ($logged?$text_checkout_payment_address:$text_checkout_account); ?></span></div>
   <div class="checkout-content"></div>
</div>