OR statement returning wrong number

前端 未结 4 651
悲&欢浪女
悲&欢浪女 2021-01-29 15:41

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         


        
4条回答
  •  天涯浪人
    2021-01-29 16:13

    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.


    Another side note.. since you like python, that code could be converted into this single line:

    $f = ($e==3 || $e==4) ? 4 : $e;
    

提交回复
热议问题