【发布时间】:2020-03-12 16:26:32
【问题描述】:
我正在努力让PHP 验证值中的负值、数字和非数字以及空值。
如果值为负、空、非数字,我需要 php 显示错误消息。
我还遇到了一个问题,即无法从$_POST 中的HTML 表单中获取值。
$first = $_POST['first'];
$second = $_POST['second'];
$operation = $_POST['operation'];
在我的表单中,每个值的名称都正确拼写为我拥有的负值
if ($first || $second < 0) {
print("<h2> Error one or more inputs are not negative numbers</h2>");
echo("<a href="calculator.html"></a>");
}
对于我有的空数字:
if (empty($first) || empty($second) == true) {
print("<p> One or more input field is empty </p>");
echo("<a href="calculator.html"></a>");
}
对于非数字值:
if (!is_numeric($first) || !is_numeric($second) == false) {
print("<h2> Error one or more inputs are not numbers</h2>");
echo("<a href="calculator.html"></a>");
}
我的问题是,每次输入任何数字时,如果是 true 或 false,我都会收到错误消息。
【问题讨论】:
-
“我的问题是,每次输入任何数字时,我都会收到错误消息,无论是真是假” - 究竟是什么?
-
if ($first or $second < 0) -
您的
!is_numeric ... == false是双重否定的。你为什么用那个? -
您需要将条件应用于您正在测试的每个值,例如
if ($first < 0 || $second < 0)并且您不需要比较布尔值,因此只需编写if (empty($first) || empty($second))和if (!is_numeric($first) || !is_numeric($second))。注意 PHP 中的逻辑或运算符是|| -
nick 我使用的是 or 运算符来查看其中是否有人为空或负数或字符串
标签: php function if-statement include