Curtis Chong
Curtis Chong

Reputation: 811

Boolian check giving incorrect answer

I'm trying to make a reputation system:

if($upvotetruedownvotefalse == false){
    if(strpos($lines[2],$username.",") !== false){
        echo "you've already downvoted";
    }
    else{
        echo "you haven't downvoted yet";
        $lines[2] = $username.",".$lines[2];
        $lines[0] = $lines[0]-1 . "\n";
        file_put_contents( $filename , $lines);

    }
}
if($upvotetruedownvotefalse == true){
    if(strpos($lines[1],$username.",") !== false){
        echo "you've already upvoted";
    }else{
        echo "you haven't upvoted yet";
        $lines[1] = $username.",".$lines[1];
        $lines[0] = $lines[0]+1 . "\n";
        file_put_contents( $filename , $lines);
    }

}

The value of $upvotetruedownvotefalse is determined through AJAX

However these comparison operators is giving me wrong results.

For example if $upvotetruedownvotefalse = false then $upvotetruedownvotefalse == truewould be triggered. I've tested this by echoing the value of $upvotetruedownvotefalseand recieving the echo results (including the ones in the if statements)using a success function:

echo $upvotetruedownvotefalse;
success: function(response){
          alert(response);
}

Then I console.log the result and I would get this:

Falseyou haven't upvoted yet

I'm getting conflicting results. I've also tried using different types of === !=== in different places and I get either an inverted result or my success function fails

Is there something that I don't know about Boolean operators? Any help would be greatly apreciated

Upvotes: 0

Views: 46

Answers (1)

dave
dave

Reputation: 64657

If you are doing an echo, and getting False in the output, then it sounds like your variable is holding the string "False", and not the boolean value false. A non-empty string is a "truth-y" value, meaning when you do if ($some_string) it will come back true.

Quickest fix would seem to be to add this before the rest of your code:

if (strtolower($upvotetruedownvotefalse) === 'false') {
    $upvotetruedownvotefalse = false;
}
//the rest of your code here

Upvotes: 2

Related Questions