Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error if "else" begins with a new php block

Tags:

php

Just curious to know why the code below gives "unexpected T_ELSE" syntax error:

<?php if (isset($_SESSION["user_id"])) { ?>
            <h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2>
<?php } ?>
<?php else { ?>
    <form action="" method="post">
        <label for="user">User ID</label>
        <input type="text" id="user" />
        <label for="password">Password</label>
        <input type="password" id="password" />
        <input type="submit" value="Login" />
    </form>
<?php } ?>

While I keep the } else { on same line, it works fine. I mean the code below just works fine:

<?php if (isset($_SESSION["user_id"])) { ?>
            <h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2>
<?php } else { ?>
    <form action="" method="post">
        <label for="user">User ID</label>
        <input type="text" id="user" />
        <label for="password">Password</label>
        <input type="password" id="password" />
        <input type="submit" value="Login" />
    </form>
<?php } ?>
like image 940
user2358796 Avatar asked Oct 04 '22 14:10

user2358796


1 Answers

thinking a bit about this, I've come to the realization that this has to be the intended behavior.

consider the following (syntactical wrong ) example:

<?php if ($condition == true) { ?>
  <div id="first">Yey</div>
<?php } ?>
<span id="second?">where am I?</span>
<?php else { ?>
  <div id="first">Ney</div>
<?php } ?>

the span element would be in an undefined state

like image 120
cypherabe Avatar answered Oct 07 '22 20:10

cypherabe