[英]Why won't this work comparing a variable in PHP?
I could use in_array
but I tried this instead, 我可以使用
in_array
但我尝试这样做,
$_POST['stat'] == ('strength' || 'speed' || 'agility' || 'endurance')
The reason being is I decided to turn on E_ALL
, my original if
being, 原因是我决定打开
E_ALL
, if
是我的原件,
if (isset($_GET['workout'], $_POST['stat']) && $_POST['stat'] == 'strength' || $_POST['stat'] == 'speed' || $_POST['stat'] == 'agility' || $_POST['stat'] == 'endurance')
But I got 3 notices for undefined variable stat
even though I tested it with isset? 但是即使我用isset测试了它,我也收到3条未定义的变量
stat
通知?
You can't "or" strings like that: 您不能“或”这样的字符串:
$ php -a
Interactive shell
php > var_dump('a' || 'b');
bool(true)
php > var_dump('strength' || 'speed' || 'agility' || 'endurance');
bool(true);
You'd need to use in_array()
for this to work: 您需要使用
in_array()
才能工作:
if (isset($_POST['stat') && in_array($_POST['stat'], array('strength', 'speed', 'agility', 'endurance')) {
...
}
因为('strength' || 'speed' || 'agility' || 'endurance')
解析为true
(因为它是一个真实值或另一个真实值等)。
You can try this instead 你可以试试看
if (isset($_GET['workout'], $_POST['stat']))
{
// Check the value after we're sure that it's set
if ($_POST['stat'] == 'strength' || $_POST['stat'] == 'speed' || $_POST['stat'] == 'agility' || $_POST['stat'] == 'endurance')
{
}
}
The problem with this is that there is a comparison || 问题是存在比较||。 that failed to short circuit the condition
未能使条件短路
if (isset($_GET['workout'], $_POST['stat']) && $_POST['stat'] == 'strength' || $_POST['stat'] == 'speed' || $_POST['stat'] == 'agility' || $_POST['stat'] == 'endurance')
Digesting your logic, it will evaluate to if $_POST['stat']
is not set 摘要您的逻辑,它将评估是否未设置
$_POST['stat']
false && $_POST['stat'] == 'strength' // short circuit, thus will not evaluate 2nd condition
// then evaluates the ORs which happens to be $_POST['stat'] is not set thus the 3 notices
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.