PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Thursday, December 20, 2012

Weird comparison of a string in PHP



Weird comparison of a string in PHP

Say there is a dropdown named message as
<select name='message'>
<option value=0>Please select Message</option>
<option value='decoded'>Decoded</option>
<option value='processing'>Processing</option>
</select>


Now I want to validate the form and throw an error if user dint selects anything. What I wrote is.


if($message == 0)
{
echo "Error!!!";
echo "Message is not yet received";
}



Can you see anything wrong in this code?
What's happening is, for all selected values of message drop down, it throws an error!!!

it's quite surprising ... :-O


Any guesses on why is it happening...


Let me tell you...
Reason is that while comparing $message with 0, where 0 is an int, php converts string to int. that is it compares
(int) $message to 0.



To my full surprise, interger casting of any string yields 0. Which is why for all selected values, the comparison gets bypassed.


Solution to this is.

if($message == '0')
{
echo "Error!!!";
echo "Message is not yet received";
}

1 comment: