Using a variable as an operator

后端 未结 11 1476
滥情空心
滥情空心 2020-12-06 09:31

So I have something like the following:

$a = 3;
$b = 4;
$c = 5;
$d = 6;

and I run a comparison like

if($a>$b || $c>$d         


        
11条回答
  •  余生分开走
    2020-12-06 09:46

    Just to make the list complete this is the function I use. It has all the operators. Its better not to use eval(). This will be much quicker and safer.

    *--------------------------------------------------------------------------
     * checks 2 values with operator
     * you can use logical operators als well
     * returns FALSE or TRUE
     */
    function checkOperator($value1, $operator, $value2) {
        switch ($operator) {
            case '<': // Less than
                return $value1 < $value2;
            case '<=': // Less than or equal to
                return $value1 <= $value2;
            case '>': // Greater than
                return $value1 > $value2;
            case '>=': // Greater than or equal to
                return $value1 >= $value2;
            case '==': // Equal
                return $value1 == $value2;
            case '===': // Identical
                return $value1 === $value2;
            case '!==': // Not Identical
                return $value1 !== $value2;
            case '!=': // Not equal
            case '<>': // Not equal
                return $value1 != $value2;
            case '||': // Or
            case 'or': // Or
               return $value1 || $value2;
            case '&&': // And
            case 'and': // And
               return $value1 && $value2;
            case 'xor': // Or
               return $value1 xor $value2;  
            default:
                return FALSE;
        } // end switch
    

    To call it:

    $value1 = 12;
    $operator = '>';
    $value2 = 13;
    if (checkOperator($value1, $operator, $value2)) {
        ... its true
    } else {
        ... its not true
    }
    

提交回复
热议问题