PHP Question: Post Variables

29th July 2011

Question

Take the following HTML form.

  1. <form id="form" method="post" name="form">
  2. <input name="number" type="text" value="0" />
  3. <input type="submit" />
  4. </form>

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

  1. if ($_POST['number'] === 0) {
  2. echo 'number is zero';
  3. } else {
  4. echo 'number is not zero';
  5. }









 

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.

  1. if (is_numeric($_POST['number']) && (int)$_POST['number'] === 0) {
  2. echo 'number is zero';
  3. } else {
  4. echo 'number is not zero';
  5. }

Comments

Permalink

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

Mihai Baboi (Sat, 07/30/2011 - 18:56)

Add new comment

The content of this field is kept private and will not be shown publicly.