はてなあたまさんのブログです。

WEB開発勉強中でーす

PHPで文字列の演算子で計算したい時の変換方法!

**string to operatorは「安全」にswitchを使いましょ! eval()などの方法もありそうですが、

こっちが安全らしいです!**

<?php
    // Your code here!
    $en = '>=';
    
    $left = (int)3;
    $right = (int)7;
    $result = 0;
    
    switch($en){
      case ">=":
        $result = $left >= $right;
        break;
    
     case "+";
       $result = $left + $right;
       break;
        // etc...
    }
    
    if ($result) {
        echo 'true';
    } else {
        echo 'false';
    }
?>