PHP – ‘false’ is not false

Update (01/19/2016):

There is a better way – http://stackoverflow.com/questions/7336861/how-to-convert-string-to-boolean-php#answer-15075609

$result = filter_var($_REQUEST['yourvar'], FILTER_VALIDATE_BOOLEAN);

 

When passing boolean values via a POST, the receiving script interprets boolean $_REQUEST variables as Strings.

So if you pass ?send_email=false, on the back-end you must say:

 if( $_REQUEST['send_email'] == 'false'){ //Here false is a string $send_email = false; //Here you've set it to a boolean } 

If you don’t do this, and further down you check for the true/false of the variable you will get true for a string of ‘false’.

Which is why you often get a lot of php if statements doing things like this:

 if ( $somevar !== 'false' ) 

even though this looks much better:

 if( $somevar ) 

You have to treat them like strings when you pull them out of $_REQUEST and convert them to booleans if you want to use them that way in PHP.

Update:

There apparently isn’t a better way to do this – Stackoverflow

You either use the ternary to convert them from strings to booleans:

$test_mode_mail = $string === 'true'? true: false;

Or you evaluate an expression to get a boolean true or false:

$test_mode_mail = ($string === 'true');