Warning: A non-numeric value encountered

Recently updated to PHP 7.1 and start getting following error

Warning: A non-numeric value encountered in on line 29

Here is what line 29 looks like

$sub_total += ($item['quantity'] * $product['price']);

On localhost all works fine..

Any ideas how to tackle this or what it is ?


Solution 1:

Not exactly the issue you had but the same error for people searching.

This happened to me when I spent too much time on JavaScript.

Coming back to PHP I concatenated two strings with + instead of . and got that error.

Solution 2:

It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value is encountered. See this link.

Here is the relevant portion that pertains to the Warning notice you are getting:

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.

I'm guessing either $item['quantity'] or $product['price'] does not contain a numeric value, so make sure that they do before trying to multiply them. Maybe use some sort of conditional before calculating the $sub_total, like so:

<?php

if (is_numeric($item['quantity']) && is_numeric($product['price'])) {
  $sub_total += ($item['quantity'] * $product['price']);
} else {
  // do some error handling...
}