【问题标题】:check for empty value in php检查php中的空值
【发布时间】:2014-08-18 06:14:26
【问题描述】:

我正在使用 PHP 中的 empty() 函数检查一个值是否为空。这将验证以下内容为空:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

我传递的值可以是字符串、数组或数字。但是,如果一个字符串有一个空格 (" "),它就不会被认为是空的。在不创建我自己的函数的情况下检查这种情况的最简单方法是什么?我不能只做empty(trim($value)),因为$value 可以是array

编辑:我不是想问如何检查字符串是否为空。我已经知道了。我在问是否有一种方法可以将数组、数字或字符串传递给 empty(),即使传递的字符串中有空格,它也会返回正确的验证。

【问题讨论】:

  • $value 的可能值是多少?
  • @sectus 数组、数字和字符串
  • 那么几乎没有一种功能适合所有人。测试您的值是数组、数字还是字符串,并按类型相应地应用验证。
  • 答案(根据编辑):没有。

标签: php validation is-empty


【解决方案1】:

我真的更喜欢 TiMESPLiNTER 制作的功能,但这里有一个替代方案,没有功能

if( empty( $value ) or ( !is_array( $value ) and empty( trim( $value ) ) ) ) {
    echo 'Empty!';
}
else {
    echo 'Not empty!';
}

请注意,例如$value = array( 'key' => '' ) 将返回Not empty!。因此,我建议使用 TiMESPLiNTERs 函数。

【讨论】:

    【解决方案2】:

    只需编写一个适合您需要的 isEmpty() 函数即可。

    function isEmpty($value) {
        if(is_scalar($value) === false)
            throw new InvalidArgumentException('Please only provide scalar data to this function');
    
        if(is_array($value) === false) {
            return empty(trim($value));
    
        if(count($value) === 0)
            return true;
    
        foreach($value as $val) {
            if(isEmpty($val) === false)
                return false;
        }
    
        return false;
    }
    

    【讨论】:

    • 是的,这行得通,但问题具体说是... without creating my own function ...
    • 感谢 Timesplinter,但正如 Mark 指出的那样,我正在检查不使用自己的函数的最简单方法。
    • 那么你为什么不写你自己的函数呢?你灵活多了。你可以参数化一切。例如,如果值应该被修剪以与空比较等。
    • :-) 你没抓住重点。我最终可能会很容易地编写自己的函数;我只是在检查是否有任何我不知道的方法可以更轻松地完成它。就像 ctype_space 选项 jurgemaister 提到的,我完全忘记了。顺便说一句,你的功能很酷。
    【解决方案3】:

    最好的方法是创建你自己的函数,但如果你真的有理由不这样做,你可以使用这样的东西:

    $original_string_or_array = array(); // The variable that you want to check
    $trimed_string_or_array = is_array($original_string_or_array) ? $original_string_or_array : trim($original_string_or_array);
    if(empty($trimed_string_or_array)) {
        echo 'The variable is empty';
    } else {
        echo 'The variable is NOT empty';
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多