验证PHP中的数组值

I have this (note that the text box is an array)

echo "<td><input style='width:60px' type='text' name='allocas[]' id='vtext' class='sc_two' size='80' maxlength='5'></td>

then in a validation code I have the following;

if(isset($_POST['Save']))
{
    if($_POST['allocas']=='')
    {
    echo "<table border='1'><tr><td>mikies</td></tr></table>";
    echo "Empty field";} 
    else 
    {
    echo "<table border='1'><tr><td>mikies</td></tr></table>";
    echo "Saved!";}
}

My issue is ($_POST['allocas']=='' doesn't seems to be doing the job as it doesn't validate and irrespective whether I have a value in allocas or not it goes to 'else' validation and prints Saved!.

If I change the text box from an array to a standalone text by changing the name to name='allocas' instead of name='allocas[]' then it works. So the issue is my validation of array values isn't correct and struggling to find an alternative approach. can you help?

Note : All these are not hard coded and dynamically populated. (live inside an echo tag)

Thanks

Using allocas[] as the field name forces PHP to treat that as a potentially multi-valued field, and it will create an array. This array will be created regardless of how many actual fields come in with that name.

When you do

$_POST['allocas'] == ''

you're actually comparing an ARRAY to a string. Since that comparison makes no sense, PHP will type-cast the array to the raw string Array (literally the letters A, r, r, etc...), which evaluates to false.

You need to count how many values are in the array, then check those individual values for "emptiness", e.g.

if (count($_POST['allocas']) > 0) {
   ... got some values
   foreach($_POST['allocas'] as $value) {
      ... test $value
   }
}

change

name='allocas[]' 

to

name='allocas' 

in your form/input.

If your input field is an "array" you can't check it afterwards like a string.

if(isset($_POST['Save']))
{
    if(count($_POST['allocas']) == 0)
    {
        echo "<table border='1'><tr><td>mikies</td></tr></table>";
        echo "Empty field";
    } else 
    {
        echo "<table border='1'><tr><td>mikies</td></tr></table>";
        echo "Saved!";
    }
}

If you want to try whether the value is empty try follwing

if (empty($_POST['allocas']))

To check if there is a value for something in PHP, you can use the empty function. I would also recommend checking that the value is indeed an array (you never know what people will do to your form)

if(isset($_POST['allocas']) && is_array($_POST['allocas']) && !empty($_POST['allocas'])) {
    //Yay! Something is here
}

References

is_array

empty

You should iterate over each of the POST values and validate each:

// Sanity check
if(is_array($_POST['allocas'])) {
  foreach($_POST['allocas'] as $oneTextFieldsValue) {
    // Validate $oneTextFieldsValue...
  }
}