Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if/else structure within html

I am trying to figure out how I should structure an if/else statement.

I understand the basic if/esle should be as follows;

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

I'm not sure how to implement this logic into my current statement. I think because the php is mixed within html it's confusing me :/

I'm sure this is very wrong but could somebody please tell me how it should be structured?

  <form role="form">
    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-default <?php if ($status == '1' ) echo 'active btn-success' ; ?>">
        <input type="radio" name="status" id="option1" value="1" autocomplete="off"> Active
      </label>
      <label class="btn btn-default <?php elseif ($status == '2' ) echo 'active btn-warning' ; ?>">
        <input type="radio" name="status" id="option2" value="2" autocomplete="off"> Inactive
      </label>
      <label class="btn btn-default <?php else ($status == '3') echo 'active btn-danger' ; ?>">
        <input type="radio" name="status" id="option3" value="3" autocomplete="off"> Not Found
      </label>
    </div>
  </form>

The error I see in NetBeans is;

Syntax error: unexpected elseif

Can I or should I just use an if statement on each label?

like image 791
jonboy Avatar asked May 05 '26 03:05

jonboy


1 Answers

Ravi Hirani has already answered the question, but I thought i'd explain why you are getting the error.

The reason is that you are not using the correct syntax. If we pull out the PHP and strip off the HTML, you might be able to see why:

if ($status == '1' ) echo 'active btn-success' ;
elseif ($status == '2' ) echo 'active btn-warning' ;
else ($status == '3') echo 'active btn-danger' ;

As you can see, you are just missing the brackets to complete the syntax required for the if statements. It should look like (without the markup):

if ($status == '1') {
    echo 'active btn-success';
} elseif ($status == '2') {
    echo 'active btn-warning';
} else ($status == '3') {
    echo 'active btn-danger';
}

Now, when including HTML, that can get quite messy! Especially when trying to track opening and closing brackets across many lines of markup. So I usually use the alternate syntax when working with markup, just to make it a little tidier! Which can be found here:

http://php.net/manual/en/control-structures.alternative-syntax.php

All you simply do is swap out the brackets with the alternative characters:

if ($status == '1'):
    echo 'active btn-success';
elseif ($status == '2'):
    echo 'active btn-warning';
else ($status == '3'):
    echo 'active btn-danger';
endif;
like image 136
Othyn Avatar answered May 07 '26 19:05

Othyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!