PHP中字符串如何与整数比较大小,存在哪些差异?

2026-04-02 12:271阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计271个文字,预计阅读时间需要2分钟。

PHP中字符串如何与整数比较大小,存在哪些差异?

我无法理解为什么声明在两次都成真。$hello=foo;if($hello=6){echo yes;我无法理解为什么声明在两次都成真.$hello=foo;if($hello=0){echo ohh yess!;}它输出了yesohh yess!我知道这是整数和字符串之间的‘差异。

我无法理解为什么声明在两次都成真.$hello=foo;if($hello=6){echoyes\n;

我无法理解为什么声明在两次都成真.

PHP中字符串如何与整数比较大小,存在哪些差异?

$hello="foo"; if($hello<=6){ echo "yes\n"; } if ($hello>=0) { echo "ohh yess!"; }

它输出

yesohh yess!

我知道这是整数和字符串之间的非法比较,但为什么它毕竟是真的.

解决方法:

正如PHP manual所说:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

在这种情况下,字符串foo在完成比较时评估为零,因此if条件将评估为TRUE.

实际上,你会做:

if(0 <= 6) { echo "yes\n";}if (0 >= 0) { echo "ohh yess!";}

如果要确保也考虑变量类型,请使用===运算符.

本文共计271个文字,预计阅读时间需要2分钟。

PHP中字符串如何与整数比较大小,存在哪些差异?

我无法理解为什么声明在两次都成真。$hello=foo;if($hello=6){echo yes;我无法理解为什么声明在两次都成真.$hello=foo;if($hello=0){echo ohh yess!;}它输出了yesohh yess!我知道这是整数和字符串之间的‘差异。

我无法理解为什么声明在两次都成真.$hello=foo;if($hello=6){echoyes\n;

我无法理解为什么声明在两次都成真.

PHP中字符串如何与整数比较大小,存在哪些差异?

$hello="foo"; if($hello<=6){ echo "yes\n"; } if ($hello>=0) { echo "ohh yess!"; }

它输出

yesohh yess!

我知道这是整数和字符串之间的非法比较,但为什么它毕竟是真的.

解决方法:

正如PHP manual所说:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

在这种情况下,字符串foo在完成比较时评估为零,因此if条件将评估为TRUE.

实际上,你会做:

if(0 <= 6) { echo "yes\n";}if (0 >= 0) { echo "ohh yess!";}

如果要确保也考虑变量类型,请使用===运算符.