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


How to get index's value from $_POST using foreach

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

请更正我的代码。

foreach ($_POST as $vals) {
  if (is_numeric($vals)) {
    if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
    //do something
  } 
}
$_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
    }   
}

尝试:

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

比较按键

试试这个:

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

以下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值需要一些验证,但我相信你已经准备好了。