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

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

问题描述

我有一个函数 isNotEmpty 如果字符串不为空则返回真,如果字符串为空则返回假.我发现如果我通过它传递一个空字符串它不起作用.

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/>";
}

如果字符串为空,则 else 不会执行,我不明白为什么,请有人对此有所了解.

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 !== '')

因为 != '' 将返回 true 如果您传递的是数字 0 和其他一些由于 PHP 的自动类型转换.

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天全站免登陆