如何使用foreach从$ _POST获取索引值

时间:2012-06-26 16:09:44

标签: php

我想知道正确的代码,只能检测来自表单的数字$ _POST字段。

请更正我的代码。

foreach ($_POST as $vals) {
  if (is_numeric($vals)) {
    if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
    //do something
  } 
}

5 个答案:

答案 0 :(得分:4)

$_POST = array_filter($_POST, "is_numeric");

以上将删除所有非数字数组项。

foreach (array_filter($_POST, "is_numeric") as $key => $val)
{   
    // do something
    echo "$key is equal to $val which is numeric.";  
}

<强>更新

如果你只想要那些像$ _POST [1],$ _POST [2]等那样的话。

foreach ($_POST as $key => $vals){
    if (is_numeric($key)){
      //do something
    }   
}

答案 1 :(得分:1)

试试这个:

foreach ($_POST as $key => $val)
{   
  if (is_numeric($key))
  {
    // do something
  }   
}

答案 2 :(得分:1)

尝试:

 foreach ($_POST as $key => $vals){
     //this is read: $_POST[$key]=$value   
     if (is_numeric($vals) && ($vals!="0")){
          //do something
     }   
 }

答案 3 :(得分:1)

if(isset($_POST)){
   foreach($_POST as $key => $value){
       if(is_numeric($key)){
          echo $value;
       }
   }
}

比较按键

答案 4 :(得分:0)

以下使用isset()尝试处理数组的代码无效。

if(isset($_POST)){   //isset() only works on variables and array elements.
   foreach($_POST as $key => $value){
       if(is_numeric($key)){
          echo $value;
       }
   }

foreach ($_POST as $key => $val)
{   
  if (is_numeric($key))
  {
    // do something
  }   
}

更好,但现在foreach将制作$ _POST的副本并在循环期间输入内存(编程PHP:第6章,第128-129页)。我希望缓冲区溢出或内存不足错误不会跳起来咬你。 : - )


在开始之前使用is_array(),empty(),count()和其他人确定关于$ _POST的一些事实可能更明智,例如......

if(is_array($_POST) && !empty($_POST))
{
    if(count($_POST) === count($arrayOfExpectedControlNames))
    {   
        //Where the the values for the $postKeys have already been validated some...

        if(in_array($arrayOfExpectedControlNames, $postKeys))
        {
            foreach ($_POST as $key => $val)  //If you insist on using foreach.
            {   
                if (is_numeric($key))
                {
                   // do something
                }
                else
                {
                   //Alright, already. Enough!
                }   
            }
        }
        else
        {
             //Someone is pulling your leg!
        }
    }
    else
    {
        //Definitely a sham!
    }
}
else
{
    //It's a sham!
}

尽管如此,$val值还需要进行一些验证,但我确信您已接受验证。

相关问题