Reputation: 31
Thank you so much for reading and responding if you can.
Within that function's if statement, I want to test based off the strings boolean value of 'true' or 'false'
$email_form_comments = $_POST['comments']; // pull post data from form
if ($email_form_comments) $comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true
else $error = true; // if not, error set to true.
test_another_condition($comments_status); // pass $comments_status value as parameter
function test_another_condition($condition) {
if($condition != 'true') { // I expect $condition to == 'true'parameter
$output = "Your Condition Failed";
return $output;
}
}
My thinking is that $condition will hold a 'true' value, but this is not so.
Upvotes: 2
Views: 6948
Reputation: 393
I think the key here is PHP will evaluate empty strings as false and non-empty strings as true, and when setting and comparing booleans make sure to use constants without quotes. Use true
or false
not 'true'
or 'false'
. Also, I suggest writing your if statements so they will set alternate values on a single variable, or in the case of a function return an alternate value when the condition fails.
I made some small modifications to your code so that your function will evaluate true
// simulate post content
$_POST['comments'] = 'foo'; // non-empty string will evaluate true
#$_POST['comments'] = ''; // empty string will evaluate false
$email_form_comments = $_POST['comments']; // pull post data from form
if ($email_form_comments) {
$comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true
} else {
$comments_status = false; // if not, error set to true.
}
echo test_another_condition($comments_status); // pass $comments_status value as parameter
function test_another_condition($condition)
{
if ($condition !== true) {
return 'Your Condition Failed';
}
return 'Your Condition Passed';
}
Upvotes: 1