How to use if condition inside string in php

前端 未结 3 719
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 06:02

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


        
相关标签:
3条回答
  • 2021-01-17 06:38

    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";
    
    0 讨论(0)
  • 2021-01-17 06:48

    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.

    0 讨论(0)
  • 2021-01-17 06:51

    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";
    
    0 讨论(0)
提交回复
热议问题