Jump to content

Validation: How can I distinguish between "" and 0?


Grogs

Recommended Posts

At the moment I'm trying to use the following code:

 

      $required_fields= array("menu_name", "position", "visible");
      foreach($required_fields as $fieldname) {
         if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
            $errors[] = $fieldname;
         }
      }

 

It cycles through the post variables which are listed in the $required_fields array and tries to check if they contain a value. The problem is with the  (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)  part. PHP classifies 0 as empty, so I thought I could specifically check if the value was 0, and that would solve it. (I'm sending boolean values as well as strings.) This doesn't work though, if I send a string with no value, it is accepted. So, I need a way for PHP to distinguish between actual nothing, and a 0 tinyint value.

 

I tried the following in place of the if statement:

 

if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_int($_POST[$fieldname]))) {

 

This also didn't fix the problem. It then rejects an empty string as it should, but doesn't reject a value of 0. How can I distinguish between 0 and ""?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.