简体   繁体   中英

Why won't this work comparing a variable in PHP?

I could use in_array but I tried this instead,

$_POST['stat'] == ('strength' || 'speed' || 'agility' || 'endurance')

The reason being is I decided to turn on E_ALL , my original if being,

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?

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM