0

I have this code where if something then display a link, else display another link. the if and else are php code, and the links are html as you will know, but I was wondering how do you make it so it will not give me any errors, how do I combine php with 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>;

  }
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
FangXIII
  • 71
  • 4
  • 10

4 Answers4

1

This might help you. This one is from the basics of 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>";
     }
}
?>
Mamun
  • 66,969
  • 9
  • 47
  • 59
rranj
  • 288
  • 1
  • 5
  • 16
0

Remember PHP should be surrounded by <?php ?>. Simply end the "PHP part" and then start it again when you finished your 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><?

      }

Also, you can write HTML in echo statement, but you should escape some special characters like " to not interfere with the php code itself.

      <?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>";

      }

See http://php.net/manual/en/function.echo.php to more information.

barbarity
  • 2,420
  • 1
  • 21
  • 29
0

Try this

<?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 }
Bhavya Shaktawat
  • 2,504
  • 1
  • 13
  • 11
0

Use alternate syntax:

<?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; ?>
Vladimir Ramik
  • 1,920
  • 2
  • 13
  • 23
  • Alternate syntax requires closures for loops and conditionals. Else and elseifs can be placed inside if statements so long as they use : – Vladimir Ramik Mar 07 '15 at 17:20