【问题标题】:In if condition pass post value with condition operrator在 if 条件下使用条件运算符传递 post 值
【发布时间】:2014-12-11 13:17:47
【问题描述】:

我想从表单输入中发布条件运算符。并且在 IF 条件下使用张贴的运算符。无法执行任何逻辑来完成它。

<form action="" method="post" accept-charset="utf-8">
        <input name="postvalue"  size="5" maxlength="7" value=">=5">
            <p><input type="submit" value="Go"></p>
</form>

<?php 
if(10 $_POST["postvalue"]) {
    echo "Its greater than 5";
} else {
    echo "Its less than 5";
}


?>

【问题讨论】:

  • 啊,我明白了……你需要为此创建一个函数……

标签: php if-statement conditional-statements conditional-operator


【解决方案1】:

你可能正在寻找这样的东西:

<form action="" method="post" accept-charset="utf-8">
        <input name="term"  size="5" maxlength="7" value=">=5">
            <p><input type="submit" value="Go"></p>
</form>

<?php 
// separate operator and operand from the posted value
preg_match('/^([=<>!]+)([0-9]+)$/', $_POST['term'], $tokens);
$operator = $tokens[1];
$operand  = $tokens[2];

// create an evaluation function
$check = create_function('$value', '
    $operand = '.$operand.';
    switch("'.$operator.'") {
    case "==": return ($value==$operand);
    case "!=": return ($value!=$operand);
    case "<":  return ($value<$operand);
    case "<=": return ($value==$operand);
    case ">":  return ($value>$operand);
    case ">=": return ($value>=$operand);
    default:   throw new Exception("invalid operator");
  }');

// apply the evaluation function to some value
try {
  if ($check(10)) {
      echo "10 is greater than 5";
  } else {
      echo "10 is less than 5";
  }
} catch (Exception $e) {
  echo sprintf('Exception: %s', $e->getMessage());
}
?>

显然必须添加错误检测等......

无论如何,这是一个非常“奇怪”的架构......考虑其他方法,因为这种方法有点容易失败。相反,您应该将操作数和运算符发布在单独的输入字段(发布字段)中,以简化评估并使事情更加健壮。运算符可能应该作为选择输入提供,操作数作为数字微调器......

【讨论】:

  • 嘿,这有错误,但你理解我的要求。我希望我需要一些像这样或类似于我正在尝试处理的逻辑。
  • 经过一些最终调整后就好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2021-12-26
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多