Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if Else php need explanation

Tags:

php

i write a code in php and i found that there is a problem in a code like this :

<?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 this way :

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

It works.

I need a clear explanation about what caused the problem in the first version because i still convinced that both version are syntactically right!

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

I don't need any alternative solution i just wonder to know why there is a problem in the first version and what's wrong with it!

like image 687
Seif Eddine Slimene Avatar asked Dec 15 '22 06:12

Seif Eddine Slimene


1 Answers

One way to think about it is to replace ?> ... <?php with echo "...";

So your code becomes:

<?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 {
    // ...
}

Whereas if you just have } else { you don't have that extra echo "\n"; in the way.

like image 139
Niet the Dark Absol Avatar answered Dec 25 '22 09:12

Niet the Dark Absol