PHP Warning: A non-numeric value encountered 錯(cuò)誤解決辦法
PHP 7.1 后的版本,經(jīng)常收到 A non-numeric value encountered 的 warning 信息。
比如下面這段代碼:
$a = '123a';$b = 'b456';echo $a+$b;
PHP 7.1 新 E_WARNING
這是 PHP7.1 新增的 waring 信息,官方的解釋是:
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.在使用 (+ - * / ** % << >> | & ^) 這些運(yùn)算操作符時(shí),例如 a+b,如果 a(123a) 和 b(b456) 包含非數(shù)字字符時(shí),就會(huì)有 A non-numeric value encountered 警告。
解決方法
對(duì)于這種問題,首先應(yīng)該在代碼邏輯查看,為何會(huì)出現(xiàn)混合數(shù)值,檢查哪里導(dǎo)致出現(xiàn)混合數(shù)值。
對(duì)于(+ - * / ** % << >> | & ^) 的運(yùn)算,可以使用強(qiáng)制類型轉(zhuǎn)換方法 (intval),把字符串轉(zhuǎn)換成數(shù)字:
$a = '123a';$b = 'b456';echo intval($a)+intval($b);
評(píng)論
圖片
表情
