OR statement returning wrong number

前端 未结 4 600
悲&欢浪女
悲&欢浪女 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:12

    For your or statement, this is what you want:

    if ( ($e == 3) || ($e == 4) ) {
        $f=4;
    }
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-01-29 16:27

    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

    0 讨论(0)
  • 2021-01-29 16:30

    The next statement is always going to be true

    if(e== 3 or 4)
    
    0 讨论(0)
提交回复
热议问题