PHP Question: Post Variables

Question

Take the following HTML form.

<form id="form" method="post" name="form">
<input name="number" type="text" value="0" /> 
<input type="submit" />
</form>

What is the output of the following PHP code after the above form has been submitted, and why?

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.

print gettype($_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.

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.

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.

if (is_numeric($_POST['number']) && (int)$_POST['number'] === 0) {
	echo 'number is zero';
} else {
	echo 'number is not zero';
}

Comments

It will output "number is not zero", because you used the === operator. This means that it checks not only if the value is zero, but also that it is a int value (witch it isn't, because it comes as a string from the form). If you use the == operator instead, it will output "number is zero". Hope I dind't get mixed up... :D

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.