This warning was introduced in PHP 7.1 as part of stricter type handling. It occurs when you attempt to perform mathematical operations (addition, subtraction, multiplication, division) on variables that contain non-numeric values (strings, arrays, objects, etc.).
$a = "hello";
$b = 5;
$result = $a + $b; // Warning: A non-numeric value encountered
PHP 7.1 introduced stricter notices and warnings for type conversions. An E_WARNING is emitted when the string does not contain a numeric value. In PHP 7.0 and earlier, non-numeric strings were silently converted to 0 during mathematical operations without any warnings.
$total = $_POST['quantity'] + $_POST['price']; // If inputs are empty or non-numeric
$subtotal = $row[‘quantity’] * $row[‘price’]; // If DB fields contain NULL or text
$sum += $item[‘value’]; // If array value is string or empty
$result = $config[‘timeout’] * 1000; // If config value is “auto” or similar
Cast the variables to integers or floats, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$subtotal = (int)$item[‘quantity’] * (float)$product[‘price’];
Use the is_numeric() function to check if a variable is a number or a string representation of a number:
if (is_numeric($value1) && is_numeric($value2)) {
$result = $value1 + $value2;
} else {// Handle non-numeric values appropriately
$result = 0; // or throw an error
}
$result = intval($value1) + floatval($value2); //convert a string to an integer or float
$result = ($value1 ?? 0) + ($value2 ?? 0);
function safeAdd($a, $b) {
$a = is_numeric($a) ? (float)$a : 0;
$b = is_numeric($b) ? (float)$b : 0;
return $a + $b;
}
$input = filter_input(INPUT_POST, ‘amount’, FILTER_VALIDATE_FLOAT);
if (!is_numeric($value)) {
throw new InvalidArgumentException(‘Expected numeric value’);
}
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
if (!isset($item['price']) || !is_numeric($item['price'])) {
throw new InvalidArgumentException('Invalid price value');
}
$total += (float)$item['price']; } return $total;
}
function multiply(float $a, float $b): float {
return $a * $b;
}
$price = is_numeric($row[‘price’]) ? (float)$row[‘price’] : 0.0;
For maximum compatibility, always validate numeric operations regardless of PHP version.
The “Warning: A non-numeric value encountered” is PHP 7.1+’s way of helping developers write more robust code. While it can be annoying when upgrading legacy applications, addressing it properly leads to more reliable and predictable code behavior. Always prefer proper validation and type checking over warning suppression.
Work with our skilled Laravel developers to accelerate your project and boost its performance.
Copyright © 2025 Niotechone Software Solution Pvt. Ltd. All Rights Reserved.