Can anyone explain this impossible bit of PHP logic?
I am trying to debug a simple PHP script. Essentially, there is a variable that is defined with:
$variable = ($_GET['variable'] == 'true') ? TRUE : FALSE;
Then, in the view file, the following code is for displaying the field if $ variable == TRUE:
<? if ($variable == true) { ?>
<p class="box">You have imported a new plan.</p>
<? } ?>
Now, even when this variable is $ as shown by var_dump ($ variable); == FALSE, HTML is imprinted between if {} tags. For me, this defies logic. I just can't figure out this problem.
Also, this code works fine on many PHP4 and PHP5 installations, with the exception of one server running PHP5.2.
Any possible suggestions? Leads? I'm pulling my hair out trying to figure it out.
Thanks.
a source to share
The problem is this:
<? if ($variable == true) { ?>
According to PHP parse rules, the $ variable is "true" if the $ variable has not been assigned either "false" or "null".
PHP true is basically useless for comparisons, since an ANY value that can be applied to a nonzero / non-null / non-false type will evaluate to a boolean true.
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";
leads to:
7: true
-1: true
0: false
null: false
true: true
abc: true
array: false
a source to share
Read the following first: http://www.php.net/manual/en/language.types.boolean.php
It seems to me that you have two versions of the truth. The first step in finding a value $_GET['variable']
is to look up the string ' true
' and assign a constant $variable
. The string ' true
' is irrelevant to logical truth in this case. Anything except the string "true" will result in the constant being assigned FALSE.
TRUE and FALSE are predefined constants in php.
The use of the $ variable must not compare against true or false. Just use if($variable)
instead.
SaltLake is right that you should check your short tags. I use <?php ?>
instead of being safe.
a source to share