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

  }
3

4 Answers 4

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>";
     }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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 }

Comments

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

1 Comment

Alternate syntax requires closures for loops and conditionals. Else and elseifs can be placed inside if statements so long as they use :

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.