PHP检查数组中的空发布数据

时间:2016-01-25 04:12:50

标签: php

HTML标记

<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..

我将这两个数组数据从jquery传递给php,我需要检查该字段是否为空,并在找到其中一个为空时退出。

但我不想一个接一个地做,可以通过像foreach或其他的php函数来完成吗?

这是我尝试但失败的原因。

$data_one = $_POST['one'];
$data_two = $_POST['two'];

if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
    exit('some field are empty');
} else {
    echo('field are filled');
    // continue other function
}

以上代码保留返回field are filled消息,无论我是否填写输入字段。

非常感谢。

4 个答案:

答案 0 :(得分:3)

$allFilled = true;
foreach($_POST['one'] as $key=>$value){
    if(empty($value)){
        $allFilled = false;
        exit('some fields are empty');
    }
}
if($allFilled){
    exit('all fields are filled');
}

答案 1 :(得分:2)

使用array_filtercount函数

<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables

$data_two = $_POST['two'];

if (count($data_one_filter) === $data_one_count) { 
    exit('fields are filled');
} else {
    echo('some fields are empty');
    // continue other function
}

答案 2 :(得分:0)

您正在以数组形式发送数据。因此,您可以将此数据检查为以下数组:

$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];

if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
    exit('some field are empty');
} else {
    echo('field are filled');
    // continue other function
}

答案 3 :(得分:0)

试试这个

foreach($_POST['one'] as $key=>$value){
    if(empty($value)){
        exit('some field are empty');
    }
}

echo "All fields are filled";