dqz30992 2013-07-23 16:53
浏览 52
已采纳

验证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

  • 写回答

6条回答 默认 最新

  • dscizpq790832708 2013-07-23 16:58
    关注

    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
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料