1

I have two variables

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

I'm trying to echo only if the variable is exist so I wrote this statement

<?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 } ?>

But now when $male and $female exist
the elseif is also true, How can I fix it?

0

4 Answers 4

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>';
Sign up to request clarification or add additional context in comments.

1 Comment

Seems a bit like overkill but I've always thought overkill is underrated
2

You can use the isset() to test if the variable exist or null

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

1 Comment

if(isset($male)&&isset($male)){ looks like a perfect way to SUPER check if the variable really, REALLY exists. /s
1

You could use implode. You can also throw in some error checking.

$greeting = array();
if (!empty($_GET["male"]))
    $greeting[] = $_GET["male"];
if (!empty($_GET["male"]))
    $greeting[] = $_GET["male"];

if (count($greeting) > 0)
    echo "<h1>Welcome, " . implode(" & ", $greeting) . "!</h1>";
else
    echo "<h1>Who's there?</h1>";

Comments

0

Add not male and not female to the elseif. Like this:

<?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 } ?>

4 Comments

OK, but I get also error when I'm defining the 2 variables, for example if the female is not exist I get:"Undefined index: female in .... "
Your problem already starts with $male = $_GET["male"];. If there is no GET parameter male you'll get an undefined index error.
OK, what is the suggestion? to use what?
My solution, obviously ;-) For your solution you should replace $male = $_GET["male"]; by $male = $_GET['male'] ?? null; (see Null coalescing operator for a pre php7 version of that) and $female = ... correspondingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.