If Else php needs an explanation

I am writing code in php and I found that there is a problem in the code:

<?php if(isset($_GET['f'])) { ?>
    <?php if($_GET['f']=="message_reçus") { ?>
        -- another code here --
    <?php } ?>
<?php } ?>  
<?php else { ?>

But when I just write it like this:

<?php if(isset($_GET['f'])) { ?>
    <?php if($_GET['f']=="message_reçus") { ?>
        -- another code here --
    <?php } ?>  
<?php } else { ?>

He works.

I need a clear explanation of what caused the problem in the first version, because I'm still convinced that both versions are syntactically correct!

PHP Parser shows me: syntax error: syntax error, unexpected 'else' (T_ELSE)

I don’t need any alternative solution, I’m just interested to know why there is a problem in the first version and what is wrong with it!

+4
source share
2 answers

One way to think is to replace ?> ... <?phpwithecho "...";

So your code will look like this:

<?php
if(isset($_GET['f'])) {
    echo "\n\t";
    if($_GET['f'] == "message_reçus") {
        echo "\n\t\t";
        // more code here
        echo "\n\t";
    }
}
echo "\n"; // problem!
else {
    // ...
}

} else {, echo "\n";.

+12

@NietTheDarkAbsol. , , .

exlained ( @NietTheDarkAbsol )

, \n , else if.

<?php if ($a === $b) { ?>  
<?php } ?>  
<?php else { ?>

if ($a === $b) { \n } \n else {

\n if , else if .

.

, HTML PHP, , . , .

<?php if(isset($_GET['f'])) : // Colon instead of an '{' ?>
    <?php if($_GET['f']=="message_reçus") : ?>
        <!-- HTML here -->
    <?php else : ?>
        <!-- alternative HTML here -->
    <?php endif; // endif; instead of an '}' ?>
<?php endif; ?>

, , endif;, else : elseif (...) :.

0

All Articles