如何解决致命错误:未捕获的类型错误:不支持的操作数类型:PHP 8.0.8 上的 int + string
我正在将像 35,578,926 这样的数字格式转换为像 35.5M(或百万)这样的短字。我的代码在 PHP 7.4 上运行良好,在最新版本 8.0.8 上出现致命错误。
function convert($n)
{
$n = (0 + str_replace(",","",$n));
if (!is_numeric($n)) return false;
if ($n > 1000000000000) return round(($n / 1000000000000),1) . 'T';
else if ($n > 1000000000) return round(($n / 1000000000),1) . 'B';
else if ($n > 1000000) return round(($n / 1000000),1) . 'M';
else if ($n > 1000) return round(($n / 1000),1) . 'K';
return number_format($n);
}
$n = '35578926';
在 PHP 7.4 上,此代码返回输出:
$n = convert('35578926');
echo $n; // 35.5M
我尝试改变
$n = (0 . str_replace(",$n)); // this resolve nothing but no error
$n = null; // also this resolve nothing but no error
那么我如何在 PHP 8.0.8 上将这个数字(35578926 或 35,926)转换成像 35.5M 这样的短字?
解决方法
我怀疑这行代码是由比 PHP 更熟悉 JavaScript(或其他语言)的人编写的:
const arr = ["Giraffe","Camel","Dog","Lion"].sort()
arr.forEach((word) => {
document.getElementById("animal-container").appendChild(
<div class="animal-cards">
<div class="img-container">
<img src="#">
</div>
<div class="animal-info">
<div class="animal-name">{word}</div>
</div>
)})
在 JavaScript 中,这里的“0 +”是一种将值强制为“数字”而不是字符串的惯用方式。但是,在 PHP 中,有 explicit cast operators 用于此目的,以及单独的整数和浮点类型,因此该行应该是:
$n = (0 + str_replace(",","",$n));
或:
$n = (int)str_replace(",$n);
这里还有一个bug,就是这条线发生得太晚了:
$n = (float)str_replace(",$n);
目前,这是在将字符串转换为数字之后运行的,因此它不可能不是数字。这会更有意义:
if (!is_numeric($n)) return false;
请注意,is_numeric 对“数字”的定义非常广泛,因此如果您实际上只想要整数,则可能需要 ctype_digit 来代替:
$n = str_replace(",$n);
if (!is_numeric($n)) return false;
$n = (float)$n;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。