PHP 7.3.8 中遇到的非数值

A non-numeric value encountered in PHP 7.3.8

我的以下代码 returns 0 在我的生产服务器上有预期的 PHP 7.0 但在我的本地主机上 returns "A non-numeric value encountered" - PHP 7.3.8 .

<?php
ini_set("log_errors"     , "1");
ini_set("error_log"      , "errors.log");
ini_set("display_errors" , "1");

$f['Customers2'] = "";
$f['MonetarySpend'] = "";
echo str_replace(',', '', $f['MonetarySpend']) *  str_replace(',', '', $f['Customers2']);
?>

如何在 PHP 7.3.8 中将 "" 视为 0?

这个警告是 implemented in PHP 7.1

您可以使用显式转换而不是期望隐式转换。

echo intval(str_replace(',', '', $f['MonetarySpend'])) * intval(str_replace(',', '', $f['Customers2']));

如果钱可以带小数,可以用floatval代替

echo floatval(str_replace(',', '', $f['MonetarySpend'])) * floatval(str_replace(',', '', $f['Customers2']));

如果这让您感到困扰,而您只想乘车一次警告信息,您可以使用@作为error control operator :

echo @(str_replace(',', '', $f['MonetarySpend']) *  str_replace(',', '', $f['Customers2'])); // no warning

使用 php 7.3.5 的一些示例:

echo "Operations with ints : " . intval(str_replace(',', '', "12,345")) * intval(str_replace(',', '', "42")) . PHP_EOL;
echo "Operations with empty strings : " . intval(str_replace(',', '', "")) * intval(str_replace(',', '', "")) . PHP_EOL;

echo "Operations with floats : " . floatval(str_replace(',', '', "12,345.67")) * floatval(str_replace(',', '', "42")) . PHP_EOL;
echo "Operations with empty strings : " . floatval(str_replace(',', '', "")) * floatval(str_replace(',', '', "")) . PHP_EOL;

echo "Error control : " . @("" * "") . PHP_EOL;

echo "Now, no error control to check if I have warning enabled" . PHP_EOL;
echo "NO error control : " . "" * "" . PHP_EOL;

这输出:

Operations with ints : 518490
Operations with empty strings : 0
Operations with floats : 518518.14
Operations with empty strings : 0
Error control : 0
Now, no error control to check if I have warning enabled
<br />
<b>Warning</b>:  A non-numeric value encountered in <b>[...][...]</b> on line 
<b>12</b><br />
<br />
<b>Warning</b>:  A non-numeric value encountered in <b>[...][...]</b> on line 
<b>12</b><br />
NO error control : 0