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方法進行強制轉為數值型后,可以解決警告提示問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM