gpt4 book ai didi

PHP 比较运算符和数据类型

转载 作者:行者123 更新时间:2023-12-04 07:01:41 25 4
gpt4 key购买 nike

我目前正在研究 O'Reilly 的“PHP 编程”,并遇到了这个名为“比较运算符执行的比较类型”的表格:

第一个操作数 |第二个操作数 |比较
-------------------------------------------------- ---------------------
数量 |数量 |数字
数字字符串 |数字字符串 |数字
数字字符串 |数量 |数字
非数字字符串 |数量 |辞典
数字字符串 |非数字字符串 |辞典
非数字字符串 |非数字字符串 |辞典

我对执行哪种类型的比较的经验法则是“数字当且仅当至少一个操作数是数字或两个操作数都是数字字符串时”。这似乎得到了 php.net page on Comparison Operators 的支持,其中指出“如果将整数与字符串进行比较,则该字符串将转换为数字。如果比较两个数字字符串,则将它们作为整数进行比较。”

但是,这意味着表第四行中的比较应该是“数字”。表格是否包含错误,还是我的规则有误?

最佳答案

编辑:基于评论的完整面孔。

你的总结是正确的,表格是错误的。如果一个操作数是数字,则尝试对字符串开头的数字位进行转换。如果没有数字领导者,则转换返回零。转换发生在小数和计算的有理结果中,而不仅仅是整数。

下面的代码演示了这些行为

if (2 > '10 little pigs')
print 'Integer does not coerce string'."\n";
else
print 'Integer does coerce string'."\n";

if (2.5 > '10 little pigs')
print 'Decimal does not coerce string'."\n";
else
print 'Decimal does coerce string'."\n";

if (5/3 > '2 little pigs')
print 'Rational result does not coerce string'."\n";
else
print 'Rational result does coerce string'."\n";

if (0 == 'No little pigs')
print 'Non numeric coerced to zero'."\n";
else
print 'Non numeric not coerced'."\n";

if (-0.156 > '-127 is a minumum value of a signed 8 bit number')
print 'Negative decimal does coerce string'."\n";
else
print 'Negative decimal does not coerce string'."\n";

if ('-0.156' > '-127')
print 'Both are converted if all numeric'."\n";
else
print 'No conversion if both are all numeric'."\n";

if ('-0.156' > '-127 is a minumum value of a signed 8 bit number')
print 'Successful conversion of one does coerce the other'."\n";
else
print 'Successful conversion of one does not coerce the other'."\n";

关于PHP 比较运算符和数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1740225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com