php 出現Warning: A non-numeric value encountered問題的原因及解決方法

本文介紹php出現Warning: A non-numeric value encountered問題,用實例分析出現這種錯誤的原因,並提供避免及解決問題的方法。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');

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

echo $a+$b;
?>

以上代碼執行後會提示 Warning: A non-numeric value encountered


查看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),就會有A non-numeric value encountered警告。

解決方法

對於這種問題,首先應該在代碼邏輯查看,爲何會出現混合數值,檢查哪裏出錯導致出現混合數值。

對於(+ - * / ** % << >> | & ^) 的運算,我們也可以加入轉換類型方法,把錯誤的數值轉換。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');

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

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

加入intval方法進行強制轉爲數值型後,可以解決警告提示問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章