gpt4 book ai didi

php - PHP:检查键值不为空

转载 作者:行者123 更新时间:2023-12-02 07:04:24 24 4
gpt4 key购买 nike

我写了一个小函数来检查表单的必填字段,它们不是空的。
该函数接受两个参数,第一个是具有$ _POST超全局变量的所有值的数组。
第二个是我填充的必填字段数组。

看一看:

public $errors = array();

public function validate_fields($fields_array, $required_fields)
{
foreach ($required_fields as $key => $value)
{
if (array_key_exists($key, $fields_array))
{
# If key exists in $fields_array
# check that the key value inside $fields_array is set & isn't empty
# if it's empty, populate with an error
if(empty($fields_array[$key][$value]))
{
$this->errors[] = "{$key} is empty but in fields_array";
}
}
else
{
# Key does not exists in $fields_array
# Did someone temper with my html ?
$this->errors[] = "{$key} is not in fields_array";
}
}
return (empty($this->errors)) ? true : false;
}

我遇到的问题似乎与“if(empty($ fields_array [$ key] [$ value]))”有关
声明。我的目标是根据$ required_fields键检查$ fields_array键值是否为空。我确定我正在使用的语句已关闭。如果您发现任何您认为可以写得更好的东西,请告诉我,因为我是php新手。感谢帮助。

最佳答案

我认为您正在尝试做的是:

if(empty($fields_array[$key])) {
//this means value does not exist or is FALSE
}

如果您还只想检查空字符串或空格,那么您需要的不只是空字符串。例如。
if(empty($fields_array[$key]) || !trim($fields_array[$key]))         {
//this means key exists but value is null or empty string or whitespace only
}

关于php - PHP:检查键值不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com