cgwebprojects
cgwebprojects

Reputation: 3482

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?

Upvotes: 0

Views: 73

Answers (4)

mdprotacio
mdprotacio

Reputation: 842

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

Upvotes: 0

Fad
Fad

Reputation: 9858

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')
    {

    }
} 

Upvotes: 0

Marc B
Marc B

Reputation: 360862

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')) { 
 ...
}

Upvotes: 3

Quentin
Quentin

Reputation: 944443

Because ('strength' || 'speed' || 'agility' || 'endurance') resolves as true (since it is a true value or another true value or etc).

Upvotes: 1

Related Questions