sniper
sniper

Reputation: 2943

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :

$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
    echo "blah";
}
else
{
    echo "foo";
}

Why does the if condition pass? Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?

Upvotes: 4

Views: 380

Answers (9)

Calvin Davis
Calvin Davis

Reputation: 288

The problem here is that you're putting your expressions in strings!

Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.

To fix this you just need to take your expressions out of the strings. It should look like this:

$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false

if ($condition) {
    echo 'blah';
} else {
    echo 'foo'; // This will be output
}

Upvotes: 8

Glass Robot
Glass Robot

Reputation: 2448

All $condition* variables will evaluate to true. This is how PHP sees it:

if("53==56" || "53==57" || "53==58")

What you want is this:

$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;

Upvotes: 4

switz
switz

Reputation: 25188

Because you're not checking those variables, it's saying if (String) will always return true. (unless "")

You should be doing:

if(53==56 || 53==57 || 53==58)
{
    echo "blah";
}
else
{
    echo "foo";
}

Upvotes: 4

slier
slier

Reputation: 6740

String always evaluate to true if its not empty
And btw php make implicit conversion to boolean

Upvotes: 1

Jonathan Allard
Jonathan Allard

Reputation: 19249

Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).

Upvotes: 1

Femaref
Femaref

Reputation: 61437

You are concatting a string together, a non-empty string equals TRUE in php.

Upvotes: 2

Peter O.
Peter O.

Reputation: 32878

It's because you're evaluating a string, and strings other than empty strings evaluate to true.

Upvotes: 2

ceejayoz
ceejayoz

Reputation: 180004

Those aren't conditions, they're strings.

$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
    echo "blah";
}
else
{
    echo "foo";
}

Upvotes: 5

Wooble
Wooble

Reputation: 89867

You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.

Upvotes: 7

Related Questions