为什么检查字符串是否为空的函数总是返回true? [英] Why a function checking if a string is empty always returns true?

查看:248
本文介绍了为什么检查字符串是否为空的函数总是返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数isNotEmpty,如果字符串不为空,则返回true;如果字符串为空,则返回false.我发现如果我通过它传递一个空字符串,它将无法正常工作.

I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it.

function isNotEmpty($input) 
{
    $strTemp = $input;
    $strTemp = trim($strTemp);

    if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
    {
         return true;
    }

    return false;
}

使用isNotEmpty对字符串进行验证:

The validation of the string using isNotEmpty is done:

if(isNotEmpty($userinput['phoneNumber']))
{
    //validate the phone number
}
else
{
    echo "Phone number not entered<br/>";
}

如果字符串为空,则其他字符串不执行,我不明白为什么,请有人对此进行说明.

If the string is empty the else doesn't execute, I don't understand why, can someone please shed some light on this please.

推荐答案

实际上是一个简单的问题.更改:

Simple problem actually. Change:

if (strTemp != '')

if ($strTemp != '')

可以说,您可能还希望将其更改为:

Arguably you may also want to change it to:

if ($strTemp !== '')

因为!= ''如果您传递的是数字0以及由于

since != '' will return true if you pass is numeric 0 and a few other cases due to PHP's automatic type conversion.

不应将内置的 empty()函数用于这;请参见注释和 PHP类型比较表.

You should not use the built-in empty() function for this; see comments and the PHP type comparison tables.

这篇关于为什么检查字符串是否为空的函数总是返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆