Quick primer- How to evaluate strings to boolean in PHP

Occasionally in PHP, you need to evaluate a string value to its boolean counterpart. One very common example of when this is needed is when you try to represent boolean in query string parameters. The jury is still out on the most appropriate way to represent a boolean value in Rest API or a query string, some of the

  1. true
  2. True
  3. TRUE
  4. false
  5. FALSE
  6. Yes
  7. No
  8. On
  9. Off
  10. 0
  11. 1

all of the values listed above are valid ways to represent a boolean value in your API or query string hence the need find a valid way to change the values correctly to their boolean value.

Evaluation using filter_var()

this filter_var method has been present in PHP since php5 and as the name implies, it filters a variable with a specified filter, for the purpose of this writeup, we are interested only in the boolean filter which is named FILTER_VALIDATE_BOOLEAN.

check the example below

filter_var("1", FILTER_VALIDATE_BOOLEAN)   // => bool(true)
filter_var("on", FILTER_VALIDATE_BOOLEAN)  // => bool(true)
filter_var("false", FILTER_VALIDATE_BOOLEAN) // => bool(false)

Value (int) BoolVal Boolean
1 1 TRUE
 0 0 FALSE
true 1 TRUE
false 0 FALSE
1 1 TRUE
1 1 TRUE
on 1 TRUE
off 0 FALSE
yes 1 TRUE
no 0 FALSE
True 1 TRUE

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s