Joppo
Joppo

Reputation: 729

unexpected behaviour in if statement in php code

The console in a html file calling the php code shows the following results when the php code is executed:

php processing: debug 3: TEST IF: in IF

php processing: debug 4: false

However, I'd expect the the first console result to be php processing: debug 3: TEST IF: in ELSE. E.g., it seems that according to the console the wrong (if) part of the if-else statement is executed and I don't understand why (for this very simple code)???

Any suggestions?

Php code:

//TEST CODE
if($productselected_form[0] == true)
{
    $response_array['debug3'] = 'TEST IF: in IF';
}
else
{
    $response_array['debug3'] = 'TEST IF: in ELSE';
}
$response_array['debug4'] = $productselected_form[0];

//send the response back
echo json_encode($response_array);
//END TEST CODE

Javascript code (console.log in ajax call to php code):

console.log("php processing: debug 3: "+msg.debug3);
console.log("php processing: debug 4: "+msg.debug4);

Upvotes: 0

Views: 88

Answers (2)

Jeroen Ingelbrecht
Jeroen Ingelbrecht

Reputation: 808

The problem is you're comparing a String value to a boolean which will always evaluate to true. You should compare String to String like so

//TEST CODE
if($productselected_form[0] == 'true')

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227260

Your $productselected_form[0] is probably a string, not a boolean. When using ==, PHP converts the types so that it can compare them.

I'm guessing you have 'false', not false. When converting to boolean, the following strings are false:

  • '0'
  • '' (empty string)

Anything else is true. So when you do $productselected_form[0] == true, you are actually doing 'false' == true, which evaluates to true.


To convert 'false' to false you can do something like this:

$productselected_form[0] = ($productselected_form[0] === 'true');

Upvotes: 2

Related Questions