我想知道正确的代码来仅检测来自表单的数字 $_POST 字段。
请更正我的代码。
foreach ($_POST as $vals) {
if (is_numeric($vals)) {
if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
//do something
}
}
我想知道正确的代码来仅检测来自表单的数字 $_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 => $val)
{
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;
}
}
}
比较键
以下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
值仍然需要一些验证,但我相信你已经做到了。