PHP 函数 is_nan() 引发字符串警告
我一直在使用 is_nan() 函数(即 is-not-a-number)来检查从查询字符串中获取的变量是否是数字。然而,在变量是字符串的情况下(在这种情况下,is_nan()
应该返回 TRUE
),该函数还会抛出以下相当烦人的警告
Warning: is_nan() expects parameter 1 to be double, string given
: >is_nan() 用于检查变量是否不是数字,为什么它会抛出字符串错误?我本以为它应该接受非数字参数,因为这就是它的目的......
是否有理由抛出这样的警告?有什么我在这里没有看到的感觉吗?
注意:抛出错误时,该函数仍按预期运行 - 对于字符串返回 TRUE,对于数字返回 FALSE。但是,我想知道为什么它也会在字符串的情况下引发警告。
我也开始使用 is_int()
因为我发现它更适合我的目的,所以我不寻找替代品。我只是对这种行为感到好奇。
I've been using the is_nan()
function (i.e. is-not-a-number) to check whether a variable taken from the query string is a number or not. However, in the case of the variable being a string (in which case is_nan()
should return TRUE
), the function also throws the following rather annoying warning:
Warning: is_nan() expects parameter 1 to be double, string given
Since is_nan()
is for checking if a variable is not a number, why would it throw an error for a string? I would have thought that it should accept non-numerical parameters, since that is kind-of it's purpose...
Is there a reason why such a warning would be thrown? Is there some sense that I'm not seeing here?
Note: When the error is thrown, the function still behaves as expected - it returns TRUE for strings and FALSE for numbers. However, I am wondering why it would also throw a warning in the case of a string.
I have also since started using is_int()
because I have found it to be better suited to my purposes, and so I am not looking for alternatives. I am just curious about this behaviour.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
该函数旨在检查数学函数和运算的返回值的有效性(请参阅NaN@wikipedia )并期望一个浮点数作为参数。示例取自 函数文档:
您可能想要的是 < a href="http://www.php.net/manual/en/function.is-numeric.php" rel="noreferrer">
is_numeric()
:The function is intended for checking the validity of return values of mathematical functions and operations (see NaN@wikipedia) and expects a float as a parameter. Example taken from the function's documentation:
What you probably want is
is_numeric()
:从这里:
From here:
查看文档表明您对
is_nan()
不正确。我认为您需要使用is_int()
或is_float()
。或者,您可以使用显式强制转换来转换变量。is_nan()
是一个数学函数,而is_int()
是一个变量处理函数。A look at the documentation suggests that your understanding of
is_nan()
is incorrect. I think you need to useis_int()
oris_float()
. Alternatively you could use an explict cast to convert your variable.is_nan()
is a maths function whileis_int()
is a variable handling function.因为在这种情况下它必须执行隐式强制转换。它应该警告你。我想知道隐式转换发生在哪里。它太容易出错。
Because in this situation it has to perform implicit cast. It should warn you. I want to know where implicit casts occur. It is too prone to error.
查看:
https://www.php.net/manual/en/function。 is-nan.php
"bool is_nan ( float $val )" <- 这就是原因。
Check:
https://www.php.net/manual/en/function.is-nan.php
"bool is_nan ( float $val )" <- That's why.
如果将 is_nan() 函数包装在条件中,您是否会收到错误,例如:
Do you get the error if you wrap the is_nan() function in a conditional, like: