views:

107

answers:

4

Hi, I want to know if there is a way to use something like this:

$t1=1;
$t2=2;
$t3="$t1>$t2";

if($t3)
   echo "Greater";
else
   echo "Smaller";

This will evaluate to true as $t3 is a string, but that's wrong!!!

So is there a way to include the if condition inside string.

I heard that we can use eval for this: http://stackoverflow.com/questions/3191911/php-if-condition-inside-string

But how is this possible???

+3  A: 

For that, you don't need to evaluate a string. Just write it as a raw condition, and it'll give you a boolean which you can evaluate as is in the if condition:

$t3 = $t1 > $t2;

By the way, the else in your code will evaluate if $t1 and $t2 are equal. You can use an else if to take care of that, but it's just something I thought I'd point out.

BoltClock
@BoltClock, OP specifically wants it to be in a string,.
Jacob Relkin
Thanks, you are correct, an else if will be better, I wrote it as a general rule.
sreejith
A: 

Most likely you don't heed that and this question come out from bad design.
Why not to make it just

if ($t1>$t2) echo "greater";
Col. Shrapnel
That's Not what I wanted!!!!
sreejith
@sreejith too bad for you
Col. Shrapnel
I decided to use eval() which seems to be the better solution.
sreejith
@ WIll, @ Col. Thanks for the help.
sreejith
A: 

This looks like it should work, given the PHP eval page.

$t1=1;
$t2=2;
$t3="return $t1>$t2;";

if(eval($t3))
   echo "Greater";
else
   echo "Smaller";
Will A
Thanks, Let me see if I can make this work!
sreejith
A: 

Why do you want to do that... it smells!

It looks like you're trying to do something in a inventive but complicated way which can be done in a better, easier, more maintainable way. Would you mind sharing your intentions and reasons?

Also it is not generally advisable to use eval() at all.

tharkun
Hi,The need for something like this is that I'm looking to get these conditions from an xml file and i need a solution that I can use for an unlimited no. of checks
sreejith
Can you add that to your question and also a part of your xml file.
tharkun