php echo仅在变量存在时才显示

时间:2015-12-24 23:08:36

标签: php

我有两个变量

<?php 
    $male = $_GET["male"];
    $female = $_GET["female"];  
 ?>

我只是在变量存在时才尝试回应,所以我写了这个陈述

<?php if ( $male && $female ) { ?>
    <h1>Welcome, <?php echo $male; ?> & <?php echo $female; ?></h1>
<?php } elseif ( $male ) { ?>
    <h1>Welcome, <?php echo $male; ?></h1>
<?php } elseif ( $female ) { ?>
    <h1>Welcome, <?php echo $female; ?></h1>
<?php } else { ?>
    <h1>Weclome</h1>
<?php } ?>

但现在$male$female存在时 elseif也是如此,我该如何解决?

4 个答案:

答案 0 :(得分:2)

echo '<h1>Welcome';
$sep = array(', ', ' &amp; ');
foreach (array('male', 'female') as $param) {
    if ( isset($_GET[$param]) ) {
        echo array_shift($sep), htmlentities($_GET[$param]);
    }
}
echo '</h1>';

答案 1 :(得分:1)

您可以使用isset()来测试变量是否存在或null

if(isset($male)&&isset($male)){
<h1>Welcome, <?php echo $male; ?> & <?php echo $female; ?></h1>
}

答案 2 :(得分:1)

你可以使用implode。你也可以进行一些错误检查。

import re

pattern = 'Delivered to Mr.Smith at Seattle'

re.match(r'Delivered to (.*) at (.*)', pattern).groups()
('Mr.Smith', 'Seattle')

re.findall(r'Delivered to (.*) at (.*)', pattern)
[('Mr.Smith', 'Seattle')]

答案 3 :(得分:0)

在elseif中添加不是男性而非女性。像这样:

<?php if ( $male && $female ) { ?>
    <h1>Welcome, <?php echo $male; ?> & <?php echo $female; ?></h1>
<?php } elseif ( $male && !$female ) { ?>
    <h1>Welcome, <?php echo $male; ?></h1>
<?php } elseif ( $female && !$male ) { ?>
    <h1>Welcome, <?php echo $female; ?></h1>
<?php } else { ?>
    <h1>Weclome</h1>
<?php } ?>