views:

82

answers:

4

I'm attempting to debug a simple PHP script. Essentially, there's a variable which is defined with:

$variable = ($_GET['variable'] == 'true') ? TRUE : FALSE;

Then, in the view file, the following code is meant to display a box if $variable == TRUE:

<? if ($variable == true) { ?>
<p class="box">You have imported a new plan.</p>
<? } ?>

Now, even when that $variable, as shown by var_dump($variable); == FALSE, that HTML is printed between the if { } tags. To me, this defies logic. I simply can't figure out this problem out.

Furthermore, this code works fine on many PHP4 and PHP5 installations except for one particular server running PHP5.2.

Any possible suggestions? Leads? I'm pulling out my hair trying to figure this one out.

Thank you.

+2  A: 

Never compare for equality with true or false, only identity.

<? if ($variable) { ?>

or

<? if ($variable === true) { ?>
Ignacio Vazquez-Abrams
+2  A: 

Maybe short tags are off? Try to use

<?PHP if ( TRUE == $variable ) : ?>
    <p class="box">You have imported a new plan.</p>
<?PHP endif; ?>
SaltLake
+1  A: 

First read this: http://www.php.net/manual/en/language.types.boolean.php

It seems to me that you've got two versions of truth here. The first step, finding the $_GET['variable'] value is looking for the string 'true' and assigning a constant to $variable. The string 'true' has no relation to boolean truth in this case. Anything other than the string 'true' will result in the FALSE constant being assigned.

TRUE and FALSE are predefined constants in php.

The use of $variable should not compare with true or false. Just use if($variable) instead.

SaltLake is right that you should check your short tags. I alwasys use instead to be safe.

Mnebuerquo
+2  A: 

The problem is this:

<? if ($variable == true) { ?>

By PHP's parsing rules, $variable equals 'true' if $variable has not been assigned either the value 'false' or 'null'.

PHP's true is basically useless for comparisons, as ANY value which can be typecast to be non-zero/non-null/non-false will evaluate to boolean true.

The following:

<?php

echo '7: ', (7 == true) ? 'true' : 'false', "\n";
echo '-1: ', (-1 == true) ? 'true' : 'false', "\n";
echo '0: ', (0 == true) ? 'true' : 'false', "\n";
echo 'null: ', (null == true) ? 'true' : 'false', "\n";
echo 'true: ', (true == true) ? 'true' : 'false', "\n";
echo 'abc: ', ('abc' == true) ? 'true' : 'false', "\n";
echo 'array: ', (array() == true) ? 'true' : 'false', "\n";

results in:

7: true
-1: true
0: false
null: false
true: true
abc: true
array: false
Marc B