如何在 php 中的 if else 语句中添加 html


How to add html inside an if else statement in php?

>我有这段代码,如果某物显示一个链接,否则显示另一个链接。 if 和 else 是 PHP 代码,链接是 HTML 如您所知,但我想知道您如何制作它,以免给我任何错误,如何将 php 与 html 相结合?

  <?php foreach ($user_socs as $user_soc) { 
  if ($soca == $user_soc) {
  <a href="file.php" class="socbuttons">Leave Society</a>;
  } else {
  <a href="anotherfile.php" class="socbuttons">Join Society</a>;
  }

这可能会对您有所帮助。这个来自PHP的基础知识:

<?php foreach ($user_socs as $user_soc) { 
     if ($soca == $user_soc) { 
         echo "<a href='file.php' class='socbuttons'>Leave Society</a>";
     } else { 
         echo "<a href='anotherfile.php' class='socbuttons'>Join Society</a>";
     }
}
?>

请记住,PHP 应该被 <?php ?> 包围。只需结束"PHP部分",然后在完成HTML后再次启动它。

      <?php foreach ($user_socs as $user_soc) { 
      if ($soca == $user_soc) {
      ?> <a href="file.php" class="socbuttons">Leave Society</a> <?
      } else {
      ?> <a href="anotherfile.php" class="socbuttons">Join Society</a><?
      }

此外,您可以在echo语句中编写 HTML,但您应该转义一些特殊字符(如 "),以免干扰 php 代码本身。

      <?php foreach ($user_socs as $user_soc) { 
      if ($soca == $user_soc) {
      echo "<a href='"file.php'" class='"socbuttons'">Leave Society</a>";
      } else {
      echo "<a href='"anotherfile.php'" class='"socbuttons'">Join Society</a>";
      }

有关详细信息,请参阅 http://php.net/manual/en/function.echo.php。

试试这个

<?php foreach ($user_socs as $user_soc) { 
      if ($soca == $user_soc) { ?>
      <a href="file.php" class="socbuttons">Leave Society</a>;
 <?php          } else { ?>
      <a href="anotherfile.php" class="socbuttons">Join Society</a>;
      <?php }

使用替代语法:

<?php
      $aUserSocs = array( 'link1', 'link2', 'link3' );
      $soca = 'link2';
      $iCountUserSocs = count( $aUserSocs );
      for( $i = 0; $i < $iCountUserSocs; ++$i ):
?>
        <?php if( $soca == $aUserSocs[ $i ] ): ?>
            <a href="file.php" class="socbuttons">Leave Society</a>;
        <?php else: ?>
            <a href="anotherfile.php" class="socbuttons">Join Society</a>;
        <?php endif; ?>
    <?php endfor; ?>