Comparing BOOLEAN TRUE to INTEGER value in PHP -


i have following php (the server running version 5.3.x) in script giving me result having trouble understanding. general idea of code have "normal mode", , 2 maintenance modes. in first maintenance mode, data evaluated , can viewed admin not stored database. if set $maintenance_mode_enabled = 2;, same "preview" output should displayed specific updates database should processed. reason added ==2 comparison because found need third option after had setup true/false basic default maintenance mode. @ rate, noticed 18 records on last maintenance_mode_enabled = true; run partially updated during process, though had set maintenance_mode_enabled = 2;.

        $maintenance_mode_enabled = true;          if ($maintenance_mode_enabled){             echo "case 0\n";         }          if (!$maintenance_mode_enabled){             echo "case 1\n";         }          if ($maintenance_mode_enabled == 2){             echo "case 2\n";         } 

the output is:

case 0 case 2 

from understood, true (being boolean) not equal 3. familiar oddities when comparing false, null , 0, problem integers , true entirely new me.

any ideas why isn't working? realize can change $maintenance_mode_enabled integer instead of bolean default, , set either 0, 1 or 2 desired results, want understand why seems defy logic.

the reason happens because you're comparing boolean integer. many languages, @ core of comparison function it's casting second part of comparison boolean. non-null, non-zero, non-empty or non-false value, in case 2 "true."

as previous answer mentions change code use strict comparison. change 3 separate if-statements 1 if-elseif statement:

if ($maintenance_mode_enabled === true) {     // catches true not > 0     echo "case 0\n"; } elseif ($maintenance_mode_enabled === false) {     // catches true not = 0     echo "case 1\n"; } elseif ((int)$maintenance_mode_enabled === 2) {     echo "case 2\n"; } 

i recommend change because maintenance mode can have 1 value.

edit

i didn't realize true , 2 coexist. do:

if ($maintenance_mode_enabled) {     echo "case 0\n";     if (2 === (int)$maintenance_mode_enabled) {         echo "case 2\n";     } } else {     echo "case 1\n"; } 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -