Skip to content

Instantly share code, notes, and snippets.

@lsauer
Last active May 30, 2016 21:45
Show Gist options
  • Select an option

  • Save lsauer/6463675 to your computer and use it in GitHub Desktop.

Select an option

Save lsauer/6463675 to your computer and use it in GitHub Desktop.
PHP: Coerce / Convert boolean value to readable string format
<?//lsauer.com
//desc: 'false' converted into a string returns an empty string
// assert((string)$boolvariable == '', '"false" converted into a <string> does not return an empty string')
// assert((string)$boolvariable == '', '"true" converted into a <string> does not return "1"')
//related to: http://stackoverflow.com/questions/7336861/how-to-convert-string-to-boolean-php
//example
echo $boolvariable ? 'true' : 'false';
echo $arrayvariable['somkeyvaluelevel1']['somekeyvaluelevel2'] ? $arrayvariable['somkeyvaluelevel1']['somekeyvaluelevel2'] 'true' : 'false';
//using the ternary operator, does not yield a concise and readable solution:
//PHP provides var_export for that
printf("Hello variable, you seem to be: %s", var_export($boolvariable['somkeyvaluelevel1']['somekeyvaluelevel2'], true));
//additionally, filter_var can be repurposed
echo filter_var($boolvariable, FILTER_VALIDATE_BOOLEAN);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment