if or multiples
I'm trying to look through a mysql stored state to see whether or not they match a condition my code is here:
$stater = $this->s开发者_Python百科tate;
if ($stater == 'WA' OR
$stater == 'BC' OR
$stater == 'CA' OR
$stater == 'NV' OR
$stater == 'AZ' OR
$stater == 'ID' OR
$stater == 'OR' OR
$stater == 'UT' OR
$stater == 'MT' OR
$stater == 'NM' OR
$stater = 'wa' OR
$stater = 'bc' OR
$stater = 'CA' OR
$stater = 'nv' OR
$stater = 'az' OR
$stater = 'id' OR
$stater = 'or' OR
$stater = 'ut' OR
$stater = 'mt' OR
$stater = 'nm'){
$division = "West";
}
else{
$division="";
}
It is returning west no matter what :\ I tried changing the ='s to =='s I've tried separating each or into its own brackets ex if( ($stater='ca') || ($stater='nm')) etc but still nothing is working. Any help would be appreciated
The problem is that you're using =
instead of ==
, so $stater
is always ending up as 'WA'
. That said, it may be cleaner to use an array and in_array()
instead:
$west = array('WA', 'BC', 'CA', ...);
if (in_array($stater, $west)) {
$division = 'west';
}
You should use ==
or ===
for comparison.
Also, for your case this code will be more handy:
$stater = $this->state;
$states = array('wa',
'bc',
'ca',
'nv',
'az',
'id',
'or',
'ut',
'mt',
'nm');
if (in_array(strtolower($stater), $states))
{
$division = "West";
}
else
{
$division = "";
}
Because you are using '=' instead of '==' in IF block.
PS. This code looks better:
$stater = $this->state;
$states = array('WA', 'BC', 'CA', ...); //add all options
$division = in_array($stater, $states) ? 'West' : '';
The equality operator is ==
, not =
.
Setting a variable always returns true
, so your line $stater = 'wa'
will by default return true for that whole expression.
And have you tried switching OR
to ||
?
You confused ==
and =
. $stater = 'wa'
sets $stater
to 'wa' and evaluates it as a boolean, always returning true.
Also, you should really consider a switch statement in conjunction with strtoupper:
switch(strtoupper($this->state)) {
case 'WA':
case 'BC':
case 'CA':
case 'NV':
$division = "West";
break;
default:
$division="";
}
In an if statement you should always use two ==, not one =. One = assigns the value, which makes it true.
However, in this particular case I would do something else:
if (in_array($starter, array('WA','BC',...))) { ... }
You definitely have =
(set) confused with ==
(compare).
Regardless, I would likely use this in your situation, which is much easier to read and edit:
$valid_states = explode(',', 'WA,BC,CA,NV,AZ,ID,UT,MT,NM');
if (in_array(strtoupper($this->state), $valid_states)) {
$division = "West";
} else {
$division = "";
}
Just to have an unconventional answer here too:
if (stristr('WA BC CA NV AZ ID OR UT MT NM', $stater)) {
Is a bit compacter than the overspecific array/list check. And in this and other cases it's often sufficient to check against a list of allowed values.
精彩评论