danidacar danidacar - 1 month ago 7
PHP Question

How to handle a PHP switch with different types?

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 echo null




    switch ($value) {
    case '0' :
    echo 'zero';
    break;
    case '' :
    echo 'empty';
    break;
    case null :
    echo 'null';
    break;
    case false :
    echo 'false';
    break;
    default :
    echo 'default';
    break;
    }



    Conclusion



  • Switch/case does loose comparison.
  • Solutions: switch with ifs or if/else

  • Answer
    switch (true) {
        case $value === '0' :
            echo 'zero';
            break;
        case $value === '' :
            echo 'empty';
            break;
        case $value === null :
            echo 'null';
            break;
        case $value === false :
            echo 'false';
            break;
        default :
            echo 'default';
            break;
    }
    

    I think, it's more readable than a if-elseif-chain like given below:

    if ($value === '0') {
      echo 'zero';
    } else if ($value === '') {
      echo 'empty';
    } else if ($value === null) {
      echo 'null';
    } else if ($value === false) {
      echo 'false';
    } else {
      echo 'default';
    }
    
    Comments