Booleans

In PHP a boolean can be assigned a constant of either TRUE or FALSE, both of which are case-insensitive, which is nice. Otherwise generally speaking 0 (zero), an empty string or empty array is considered False, whilst all other values are considered True. You can read PHP: Booleans - Manual for more information but if you plan to do something "clever" then just make sure you test it!

There are times when you wish to convert a boolean into a string. By default you get "1" for True and "" for False. Here is some PHP showing this as well as two solutions to this problem:

  function getBooleanAsString1($b) {
    return (string)$b;
  }

  function getBooleanAsString2($b) {
    # var_export returns a parsable string representation of a variable
    return var_export($b, True);
  }

  function getBooleanAsString3($b) {
    # This is the conditional, ternary operator, a shortcut for an if statement
    return ($b) ? 'true' : 'false';
  }
  
  print('Boolean: ' . getBooleanAsString1(TRUE) . ' or ' . getBooleanAsString1(false) . PHP_EOL);
  print('Boolean: ' . getBooleanAsString2(TRUE) . ' or ' . getBooleanAsString2(false) . PHP_EOL);
  print('Boolean: ' . getBooleanAsString3(TRUE) . ' or ' . getBooleanAsString3(false) . PHP_EOL);

My personal preference is the ternary operator as used in getBooleanAsString3, it is short, neat and to the point, even though an if statement would be clearer, having a dedicated functions allows for a comment to explain.