-1

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: PHP - if condition inside string

But how is this possible???

3
  • look on the answer in the link you attached , this is exactly the same example eval() Commented Sep 21, 2010 at 5:26
  • 1
    Why not if ($t1 > $t2) echo "Greater" else echo "Smaller"? Commented Sep 21, 2010 at 5:27
  • sample included in the link was not working for me So, I thought of asking it again!!! Commented Sep 23, 2010 at 4:30

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

OP specifically wants it to be in a string,.
Thanks, you are correct, an else if will be better, I wrote it as a general rule.
1

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";

Comments

-1

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";

1 Comment

I decided to use eval() which seems to be the better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.