Code前端首页关于Code前端联系我们

PHP 7.1 遇到非数字值错误原因及解决方案

terry 2年前 (2023-09-25) 阅读数 45 #后端开发

将 PHP 升级到 PHP 7.1 后,经常收到警告消息遇到非数字值。例如下面的代码:

$a = '123a';
$b = 'b456';

echo $a+$b;

PHP 7.1 New E_WARNING

这是PHP7.1中新的警告信息。官方的解释是:

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

使用 (+ – * / ** % > | & ^) 当使用这些运算运算符时,例如 a+b,如果 a(123a) 和 b(b456) 不包含-数字字符,将会出现遇到非数字值警告。

解决方案

对于这类问题,首先应该检查代码逻辑,看看为什么会出现混合值,并检查混合值出现在哪里。

对于(+ – * / ** % > | & ^)的运算,可以使用强制类型转换方法(intval)将字符串转换为数字:

$a = '123a';
$b = 'b456';

echo intval($a)+intval($b);

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门