views:

446

answers:

7

When I write an if statement, I have it check a variable like so:

if(isset($_GET['username']){
 echo "set";
 } else {
 echo "unset";
}

How could I get my if statement to check if two variables are set similiar to this:

if(isset($_GET['username'] & $_GET['firstname'])){
 echo "set";
 } else {
 echo "unset";
}

So basically how do I check two things in an if statement at once?

A: 
if (isset($_GET['username']) AND isset($_GET['firstname']))
{
    echo "set";
}
else
{
    echo "unset";
}
Mez
+10  A: 

Check out the PHP Manual on control structures and logical operators:

if(isset($_GET['username']) && isset($_GET['firstname'])) {
    echo "set";
} else {
    echo "unset";
}

Using the single & is doing a bitwise operation, which is most certainly not what you want.

and is also a synonym to the && syntax, as the other answers have shown.

EDIT: As pointed out in the comments, you can check if two variables are isset by passing them both to the isset function. However, if you ever wanted to do some other sort of operation you would need to do the logical operators above.

Paolo Bergantino
Take a look at Nick Presta's answer.
nickf
I was answering the general question of "So basically how do I check two things in an if statement at once?" but I guess I'll edit my answer to include that...
Paolo Bergantino
A: 
if (isset($_GET['username']) && isset($_GET['firstname']))
{ 
    echo "set"; 
} 
else 
{ 
    echo "unset"; 
}

For reference: PHP's operators

Rob
Schnalle
You are missing an apostrophe after 'username'.Furthermore, that is not valid code at all.
Josh Leitzel
Rob
+1  A: 

Try using the && operator (logical and) rather than & (binary and)

so if isset returns true for both then the if returns true otherwise the if will return false.

Ali Lown
+2  A: 
if ( isset($_GET['username']) && isset($_GET['firstname']) )
cg
+1  A: 

yes, or

echo ( (isset($_GET['username']) && isset($_GET['firstname'])) ? "set" : "unset" );

Tony
I tend to like something like this best.
Josh Leitzel
+6  A: 
if ( isset($_GET['username'], $_GET['firstname']) ) {
    echo 'Set!';
}

isset takes multiple arguments and if multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

Nick Presta
Yeah I was about to say this myself. I can't believe all the other answers which didn't pick up on this...
nickf