php if echo something else echo else for html


php if echo something else echo else for html

我的代码是这样的,我想让分页函数返回主页上的值然后返回其他页面上的值比如page=2或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 '; } ?>

但不工作,我敢肯定是从"'"或"'"的东西我放错了,但在哪里?

不要将?>放在echo语句中。

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

您也可以通过使用echo:

关闭PHP和而不是来实现。
<?php
if (empty($_GET) || $_GET['pg'] ==1) { ?>
    HTML codes content
<?php else { ?>
    Else html codes content
<?php } ?>

您可以使用三元操作符使其更简单。另外,最好使用isset(),因为即使$_GET不为空,也不意味着$_GET['pg']存在,因此它会生成警告。

无论如何,正如上面指出的,问题是你在echo语句中使用了?>,这是不正确的。

你可以这样做:

<?php if ((isset($_GET['pg'])) && ($_GET['pg']==1)) { ?>Html codes content and php<?php } else { ?>Else html codes content and php<?php } ?>
使用三元操作符:
<?php echo ((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>

使用三元操作符和短标记:

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

您不能在echo中使用PHP代码,因为PHP将在一次传递中解释您的代码。

你的代码应该是这样的:
<?php 
    echo (empty($_GET) || ($_GET['pg']==1)) ? 
         'Html code':
         'Another HTML code';
?>

如果您需要输出一些PHP代码,总有更好的方法来完成它,您可以包含一些包含您想要添加的PHP代码的文件。

您可以这样使用。

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

注意:我使用了直接的html代码。