简体   繁体   中英

php if echo something else echo else for html

So here's my code, I try to make for my pagination function to echo something if is on homepage and echo else if is on another page like page=2 or page3 ++

<?php if(empty($_GET) or ($_GET['pg']==1)) { echo ' ?> Html codes content and php <?php '; } else { echo '?> Else html codes content and php <?php '; } ?>

But is not working, i'm sure is from the " ' " or " '' " something i put wrong but where? where or what is the problem

Don't put ?> in the echo statement.

<?php 
if(empty($_GET) || $_GET['pg'] ==1) {
    echo 'HTML codes content';
} else {
    echo 'Else html codes content';
}
?>

You can also do it by closing the PHP and not using echo :

<?php
if (empty($_GET) || $_GET['pg'] ==1) { ?>
    HTML codes content
<?php else { ?>
    Else html codes content
<?php } ?>

You can use a ternary operator to make it simpler. Also it's better to use isset() because even if $_GET is not empty, that doesn't mean that $_GET['pg'] exists, so it will generate warnings.

Anyway as pointed out above, the problem is that you are using ?> inside the echo statement, which is incorrect.

You can do for example:

<?php if ((isset($_GET['pg'])) && ($_GET['pg']==1)) { ?>Html codes content and php<?php } else { ?>Else html codes content and php<?php } ?>

Using a ternary operator:

<?php echo ((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>

Using a ternary operator and short tags:

<?=((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>

You cannot have PHP code in echo , because PHP will interpret your code in a single pass.

Your code should be like this :

<?php 
    echo (empty($_GET) || ($_GET['pg']==1)) ? 
         'Html code':
         'Another HTML code';
?>

If you need to output some PHP code, there is always a better way to accomplish it, you can include some file that contains the php code you want to add.

You can use this way.

<?php if(empty($_GET) || $_GET['pg'] ==1): ?>
    <p>HTML codes content</p> 
<?php else: ?>
    <p>Else html codes content<p>
<?php endif; ?>

Note that : I used direct html code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM