If i put 1 or 2 into this it will return 4. Why is this?I'm more used to python stuff so sorry if this is rather basic.
e = 1;
f=0;
if(e==1){f=1;}
if(e==2){f=2;}
if(e== 3 or 4){f=4;}
echo f;
答案 0 :(得分:3)
Try replacing :
if(e== 3 or 4){f=4;}
with
if(e == 3 or e == 4){ f=4; }
The value 4 is considered to be TRUE
by the language. In your code, 1 == 3
is FALSE
, so the if statement is looking at (FALSE or TRUE)
which is equals TRUE
, so f
is set to 4.
Have a look at this link re: PHP Booleans
答案 1 :(得分:1)
For your or
statement, this is what you want:
if ( ($e == 3) || ($e == 4) ) {
$f=4;
}
答案 2 :(得分:0)
If you take a look at booleans, you'll see that pretty much everything is equals to true
in php (except for those values stated in that same page). So what you really have is something like this:
if($e==3 or true)
And since anything or true
is always true
, you get that (weird, but not unexpected) result.
In case you want to check if $e
is equals to 3
or 4
, do it like so:
if($e==3 || $e==4){
Note that since these are not if..else
statements, every condition is being checked. Take a look at the expanded version:
if($e==1){
$f=1;
}
if($e==2){
$f=2;
}
if($e==3 or 4){
$f=4;
}
This /\ is different from
if($e==1){
$f=1;
}elseif($e==2){
$f=2;
}elseif($e==3 or 4){
$f=4;
}
Since the latter only checks every condition in case none of the previous fit.
$f = ($e==3 || $e==4) ? 4 : $e;
答案 3 :(得分:0)
The next statement is always going to be true
if(e== 3 or 4)