我可以使用in_array
,但我尝试了这个,
$_POST['stat'] == ('strength' || 'speed' || 'agility' || 'endurance')
原因是我决定开启E_ALL
,原来的if
,
if (isset($_GET['workout'], $_POST['stat']) && $_POST['stat'] == 'strength' || $_POST['stat'] == 'speed' || $_POST['stat'] == 'agility' || $_POST['stat'] == 'endurance')
但即使我用isset测试它,我还是收到了3个未定义变量stat
的注意事项?
答案 0 :(得分:3)
你不能“或”这样的字符串:
$ php -a
Interactive shell
php > var_dump('a' || 'b');
bool(true)
php > var_dump('strength' || 'speed' || 'agility' || 'endurance');
bool(true);
您需要使用in_array()
来实现此目的:
if (isset($_POST['stat') && in_array($_POST['stat'], array('strength', 'speed', 'agility', 'endurance')) {
...
}
答案 1 :(得分:1)
因为('strength' || 'speed' || 'agility' || 'endurance')
解析为true
(因为它是真值或其他真值等)。
答案 2 :(得分:0)
你可以试试这个
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')
{
}
}
答案 3 :(得分:0)
这个问题是比较||未能使条件短路
if (isset($_GET['workout'], $_POST['stat']) && $_POST['stat'] == 'strength' || $_POST['stat'] == 'speed' || $_POST['stat'] == 'agility' || $_POST['stat'] == 'endurance')
消化你的逻辑,如果没有设置$_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