Question
Take the following HTML form.
1 2 3 4 | <form id="form" name="form" method="post"> <input type="text" name="number" value="0" /> <input type="submit" /> </form> |
What is the output of the following PHP code after the above form has been submitted, and why?
1 2 3 4 5 | if($_POST['number']===0){ echo'number is zero';}else{ echo'number is not zero';} |
Answer
The output of the above code is "number is not zero". This happens because we are using the === operator which looks at both the value AND type of the variables. The comparison between the 'number' element of the $_POST array and the integer 0 does not return true because every value of the post array is always a string. This can be proven by using the gettype() function on the value, like this.
1 | printgettype($_POST['number']);// prints 'string' |
This is something to take into account when doing comparisons with post variables as the == operator can cause false positives to be accepted. For example, if the post array contains the value 'false' then the following code will return true.
1 | var_dump('false'==0);// prints 'boolean true' |
You might think that casting the $_POST['number'] value will fix this issue. This will work for most cases, but if a value of 'false' is entered then casting this will result in a value of 0.
1 | var_dump((int)false);// prints 'int 0' |
To get around this you need to use functions like is_numeric() to ensure that the string is a number before trying to cast it as one. The following code is the corrected version of the above block that will only print 'number is zero' if the number is, in fact, zero.
1 2 3 4 5 | if(is_numeric($_POST['number'])&&(int)$_POST['number']===0){ echo'number is zero';}else{ echo'number is not zero';} |