Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "switch(true){}" in php with a strange logic?

Tags:

php

switch(false) {
    case 'blogHitd':
        echo('ddd');
        break;
    case false:
        echo('bbbb');
        break;
    default:
        echo 'alert("error action");';
 }

-------output------

bbbb

switch(true) {
    case 'blogHitd':
        echo('ddd');        
        break;
    case true:
        echo('bbbb');
        break;
     default:
        echo 'alert("error action");';
 }

-------a strange output-------

ddd

Why, when I pass the value of true it will always select the first one?

like image 808
qidizi Avatar asked Jan 12 '12 02:01

qidizi


1 Answers

From the PHP documentation on Booleans:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

The last sentence of this quoted passage is the line of interest in your case.

like image 118
Jonah Bishop Avatar answered Sep 21 '22 03:09

Jonah Bishop