make switch use === comparison not == comparison In PHP

后端 未结 15 2032
一向
一向 2020-11-28 07:09

Is there anyway to make it so that the following code still uses a switch and returns b not a? Thanks!

$var = 0;
switch($var) {
            


        
相关标签:
15条回答
  • 2020-11-28 07:35

    Switch statement in php does loose comparisons only (==) see http://www.php.net/manual/en/control-structures.switch.php

    Use if/elseif/else if you need strict comparisons.

    0 讨论(0)
  • 2020-11-28 07:38

    Presumably you are switching on the variable and expecting integers. Why not simply check the integer status of the variable beforehand using is_int($val) ?

    0 讨论(0)
  • 2020-11-28 07:38

    Extrapolating from your example code, I guess you have a bunch of regular cases and one special case (here, null).

    The simplest I can figure out is to handle this case before the switch:

    if ($value === null) {
        return 'null';
    }
    
    switch ($value) {
        case 0:
            return 'zero';
        case 1:
            return 'one';
        case 2:
            return 'two';
    }
    

    Maybe also add a comment to remember null would unexpectedly match the 0 case (also the contrary, 0 would match a null case).

    0 讨论(0)
提交回复
热议问题