How to handle a PHP switch with different types?

后端 未结 5 1457
栀梦
栀梦 2020-12-09 17:34

How can I make the switch respect data types ( is there a workaround better then if/else ) ?

  • $value = false; // should echo false
  • $value = null; // should ec
  • 5条回答
    •  情书的邮戳
      2020-12-09 18:08

      another option, depending on what you like to look at:

      switch($foo ?: strtoupper(gettype($foo))){
          case 'bar':
          case 'bork':
              echo $foo;
              break;
      
          case 'NULL': // $foo === null
              echo 'null';
              break;
      
          case 'INTEGER': // $foo === 0
              echo 'zero';
              break;
      
          case 'ARRAY': // $foo === array()
              echo 'array';
              break;
      
          case 'STRING': // $foo === ''
              echo 'empty';
              break;
      
          case 'BOOLEAN': // $foo === false
              echo 'false';
              break;
      
          default:
              echo $foo;
              break;
      }
      

      depending on your data, you could include an underscore for added clarity, like '_NULL', but it's not as clean IMO.

      personally, I concur with the accepted answer for something like a quick null check:

      case $foo === null:
      

    提交回复
    热议问题