0

My following code returns 0 as expected on my production server having PHP 7.0 but returns "A non-numeric value encountered" on my localhost - 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']);
?>

How do I treat "" as 0 in PHP 7.3.8 ?

Cid
  • 14,968
  • 4
  • 30
  • 45
anjanesh
  • 3,771
  • 7
  • 44
  • 58
  • _“How do I treat "" as 0 in PHP 7.3.8 ?”_ - PHP already did. If you don’t like the warnings, then either disable those, or make sure your values are actually numbers, before you try to do math with them. – 04FS Sep 18 '19 at 12:19
  • These are string values containing commas passed on by users in a form which I am storing. – anjanesh Sep 18 '19 at 12:20
  • Well then convert them to numbers first? – 04FS Sep 18 '19 at 12:28

1 Answers1

1

This warning was implemented in PHP 7.1

You can use explicit conversion instead of expecting an implicit one.

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

If the money can have decimal, you can use floatval instead

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

If this bother you and you just want to get ride for one time of warning messages, you can use @ as error control operator :

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

Some examples using 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;

This outputs :

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
Cid
  • 14,968
  • 4
  • 30
  • 45