JasonDavis
JasonDavis

Reputation: 48983

Strange php if statement problem

if($country == 224 || $country == 223 || $country == 39 && $zip == '' ){
    $_SESSION['sess_msg'] = "Please enter a Valid zipcode";
    header("location: $SITE_PATH?p=account.profile.name");
    exit;
}
variable   value
--------   -----
$country     224
$zip       11111

I know that $zip isn't empty, but the code executes as if it is. I even print it out to the browser in a debugging statement to verify that it has a value.

What is causing my program to act as if $zip does not have a value?

Upvotes: 4

Views: 422

Answers (7)

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

I like the first answer but anyway wouldn't more readable:

<?php

$need_zip_code = array(224, 222, 332, 222/* etc....*/);

if (in_array($country, $need_zip_code) &&  $zip === '') {
 // do your stuff....
}


?> 

Upvotes: 5

George Stocker
George Stocker

Reputation: 57907

Have you tried using parentheses to give order to your operations?

($country == 22 || $country == 223 || $country == 39) && ($zip == '') 

Upvotes: 15

Boldewyn
Boldewyn

Reputation: 82814

The problem is the order in which PHP checks your boolean operators. First it sees a condition, then an OR, and it thinks: Heck, yeah! The condition is met. Why should I bother read and execute the rest of this stuff?

Actually, this is a feature. Think of this constellation:

if (something_probable () OR something_very_expensive_to_compute ())

Then it is nice of PHP to not evaluate the second one, if the first one already passes the test.

Try using parentheses:

if (($country == 224 || $country == 223 || $country == 39) && $zip == '' ){

Cheers,

Upvotes: 9

Tom Haigh
Tom Haigh

Reputation: 57845

&& has a higher operator precendence than || , so you are effectively saying:

if($country == 224 || $country == 223 || ($country == 39 && $zip == '' ))

Upvotes: 5

Gumbo
Gumbo

Reputation: 655755

The && operator has a higher precedence than the || operator. So your expression is equal to:

$country == 224 || $country == 223 || ($country == 39 && $zip == '')

The solution:

($country == 224 || $country == 223 || $country == 39) && $zip == ''

Upvotes: 26

Zachary
Zachary

Reputation: 6532

Yea... but are they set to one of the correct values? Country is 224 or 223 or 39 and zip is a blank string? I want to stress, zip is a "blank" string ==''.

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351698

What does it do if you change it to this?

if($country === 224 || $country === 223 || $country === 39 && $zip === '' ){
    $_SESSION['sess_msg'] = "Please enter a Valid zipcode";
    header("location: $SITE_PATH?p=account.profile.name");
    exit;
}

I am curious if the types of the variables are causing a problem here, === will compare both the value and the type of the variable.

Upvotes: 0

Related Questions