Fixing "Warning: Illegal string offset" -- (but without losing content) - php

I have searched for solution for this problem but none fix my problem.
The answers suggest that I use isset to check the array before working on it. But I will explain how it doesnt do it for me later.
Pre-req:
I've got a huge XML file from a tour & travel webservice which I would parse and convert to PHP array and later do some operation on it. (Filter tours mostly).
My Approach:
I'm using SimpleXML to load the xml and convert it to PHP array like so:
$xml = file_get_contents(APPPATH."tour.xml", true);
$xmlString = htmlentity_to_xml($xml); //custom method to clean XML
$Str = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
//converting to array
$json = json_encode($Str);
$array = json_decode($json,TRUE);
Then I'm sending this array to a fitlerTours($searchParams, $tourArray) method along with search parameters (cityName & dates) and the array itself.
Then using foreach() i'm going through each tour to look for the cityName and raising a flag if found.
The Problem
When I filter the tours (the ones which contain cityName) for dates, I'm getting this.
Severity: Warning
Message: Illegal string offset 'year'
Filename: controllers/tourFilter.php
Line Number: 78
Warning shows for offeset 'month' and 'day' also.
Here's my PHP for date filter: (Line 78 is 4th line)
if($flag == 1){
if(!empty($fromDate)){
foreach($tour['departureDates']['date'] AS $date){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
}
else{
$dateFlag = 1;
}
$flag = 0;
}
if($dateFlag == 1){//Collect tours which contain the keyword & dates to $response array
$responseArray[] = $tour;
$dateFlag = false; //Reset Flag
}
Here's the snippet of XML:
...
<departureDates>
<date>
<day>7</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>Available</departureStatus>
</date>
<date>
<day>8</day>
<month>1</month>
<year>2016</year>
<singlesPrice>12761</singlesPrice>
<doublesPrice>9990</doublesPrice>
<triplesPrice>0</triplesPrice>
<quadsPrice>0</quadsPrice>
<shipName/>
<departureStatus>SoldOut</departureStatus>
</date>
</departureDates>
...
Now if i use the solution I found by searching around is check if the array is set properly by isset() it doesn't return true and line 78 is not executed and the data is lost. But I need the data.
This happens for only keywords i search.
Any help is appreciated.

The error says that the $date var is detected as string in some point...
Characters within strings may be accessed and modified by specifying
the zero-based offset of the desired character after the string using
square array brackets, as in $str[42]. Think of a string as an array
of characters for this purpose.
See here
So try this:
if(is_array($date)){
$dateDep = strtotime($date['year'] . "-" . (($date['month']) < 10 ? "0".$date['month'] : $date['month']) . "-" . (($date['day']) < 10 ? "0".$date['day'] : $date['day']));
if(strtotime($fromDate) <= $dateDep && $dateDep <= strtotime($fromDate . "+".$range." days")){
if($date['departureStatus'] != "SoldOut"){
$dateFlag = 1;
}
}
}
else {
//If this is not an array what is it then?
var_dump($date);
}

Related

"A non-numeric value encountered" [duplicate]

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 ?
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.
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...
}
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared :)
I had this issue with my pagination forward and backward link .... simply set (int ) in front of the variable $Page+1 and it worked...
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> »</li>
<?php }
?>
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:\ampps\phpMyAdmin\libraries\DisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save's someone some trouble...
I encountered the issue in phpmyadmin with PHP 7.3. Thanks #coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably +, -, *, or /) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
You did not mean to use an operation that expects a scalar. For example, + (addition) when you meant . (concatenation).
You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
For example, if you have echo 3 + $variable and your $variable is the string "n/a", then you might decide to instead echo "not applicable". Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
Fix these warnings! In PHP 8, this becomes a fatal error: "Uncaught TypeError: Unsupported operand types".
PHP 8
Code that used to produce the warning "A non well formed numeric value encountered" in PHP 7.1-7.4 now gives this warning instead. This happens when you have a "trailing string", which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 + "30 meters";
Output:
Warning: A non-numeric value encountered in [...][...] on line X
33
Fix:
echo 3 + (float) "30 meters";
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
Solve this error on WordPress
Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694
Simple solution here!
locate a file of wp-includes\SimplePie\Parse\Date.php
find a line no. 694
you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
For others that answers here may not resolve the issue.
My issue didn't involve integers or concatenation.
My problem was a simple typo (an errant string in my code).
$conn = new PDO($details, $username, $password); -
Somehow I had entered a minus sign (-) in my code accidentally. Removing this fixed my issue. My guess is that PHP was erroring because since it saw the minus sign it expected it needed to perform some arithmetic there but there were no arguments.
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
It might be late but for those who still have been banging their head around like I was. In my case it was legacy project developed in PHP 5.6 but when I need to modify it I was running PHP 7.1. I didn't bother to change it.(Had to pay for it) So the issue is PHP 7.1 is more strict than PHP 5.6
In PHP 5.6 following is allowed.
$totalPrice = ' '
$someFoo = $totalPrice + 100
// This is totally fine. And PHP will not yell about it.
While in PHP 7.1 it will throw an error
$totalPrice = ' '
$someFoo = $totalPrice + 100
// Error : A non-numeric value encountered.
So after changing that line to $totalPrice = 0 everything worked.
Hope someone will find it useful.
Thank you everyone. I have had:
<?php echo $data['style_headerheight']-3; ?>
which gave the error:
PHP Warning: A non-numeric value encountered in framework/inc/customcss.php on line 78
To fix, I replaced that by:
<?php echo ((int)$data['style_headerheight']-(int)3); ?>
For me this happened right now because of the operator precedence. I wrote $something & BITMASK && $another_value and the binding of && was "tighter" than the one of &. Always make sure to use parentheses to avoid such problems!
Make sure that your column structure is INT.
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
I received this error after adding two formatted variables using the number_format() method. The reason is because this method usually formats your number with a , unless you specified the optional separator argument as null. For example, let's say I have the following code:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2); // 1,147.42
$transactionfee = number_format(0.02 * $subtotal, 2); // 131.13
$total = $subtotal + $vat + $transactionfee; // 6556.7 + 1,147.42 + 131.13 = ERROR
This would trigger the following error because one of the variables contains a , which is invalid for a float type:
Warning: A non-numeric value encountered ...
The number_format() method has the following method signature:
number_format(number,decimals,decimalpoint,separator).
By specifying the separator argument as '', this error could be fixed as follows:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2, '.', ''); //1147.42
$transactionfee = number_format(0.02 * $subtotal, 2, '.', ''); //131.13
$total = $subtotal + $vat + $transactionfee; // // 6556.7 + 1147.42 + 131.13 = 7835.25

Warning: A non-numeric value encountered in /.../Compiler.php on line 4503 in Opencart 2.3 [duplicate]

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 ?
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.
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...
}
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared :)
I had this issue with my pagination forward and backward link .... simply set (int ) in front of the variable $Page+1 and it worked...
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> »</li>
<?php }
?>
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:\ampps\phpMyAdmin\libraries\DisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save's someone some trouble...
I encountered the issue in phpmyadmin with PHP 7.3. Thanks #coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably +, -, *, or /) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
You did not mean to use an operation that expects a scalar. For example, + (addition) when you meant . (concatenation).
You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
For example, if you have echo 3 + $variable and your $variable is the string "n/a", then you might decide to instead echo "not applicable". Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
Fix these warnings! In PHP 8, this becomes a fatal error: "Uncaught TypeError: Unsupported operand types".
PHP 8
Code that used to produce the warning "A non well formed numeric value encountered" in PHP 7.1-7.4 now gives this warning instead. This happens when you have a "trailing string", which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 + "30 meters";
Output:
Warning: A non-numeric value encountered in [...][...] on line X
33
Fix:
echo 3 + (float) "30 meters";
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
Solve this error on WordPress
Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694
Simple solution here!
locate a file of wp-includes\SimplePie\Parse\Date.php
find a line no. 694
you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
For others that answers here may not resolve the issue.
My issue didn't involve integers or concatenation.
My problem was a simple typo (an errant string in my code).
$conn = new PDO($details, $username, $password); -
Somehow I had entered a minus sign (-) in my code accidentally. Removing this fixed my issue. My guess is that PHP was erroring because since it saw the minus sign it expected it needed to perform some arithmetic there but there were no arguments.
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
It might be late but for those who still have been banging their head around like I was. In my case it was legacy project developed in PHP 5.6 but when I need to modify it I was running PHP 7.1. I didn't bother to change it.(Had to pay for it) So the issue is PHP 7.1 is more strict than PHP 5.6
In PHP 5.6 following is allowed.
$totalPrice = ' '
$someFoo = $totalPrice + 100
// This is totally fine. And PHP will not yell about it.
While in PHP 7.1 it will throw an error
$totalPrice = ' '
$someFoo = $totalPrice + 100
// Error : A non-numeric value encountered.
So after changing that line to $totalPrice = 0 everything worked.
Hope someone will find it useful.
Thank you everyone. I have had:
<?php echo $data['style_headerheight']-3; ?>
which gave the error:
PHP Warning: A non-numeric value encountered in framework/inc/customcss.php on line 78
To fix, I replaced that by:
<?php echo ((int)$data['style_headerheight']-(int)3); ?>
For me this happened right now because of the operator precedence. I wrote $something & BITMASK && $another_value and the binding of && was "tighter" than the one of &. Always make sure to use parentheses to avoid such problems!
Make sure that your column structure is INT.
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
I received this error after adding two formatted variables using the number_format() method. The reason is because this method usually formats your number with a , unless you specified the optional separator argument as null. For example, let's say I have the following code:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2); // 1,147.42
$transactionfee = number_format(0.02 * $subtotal, 2); // 131.13
$total = $subtotal + $vat + $transactionfee; // 6556.7 + 1,147.42 + 131.13 = ERROR
This would trigger the following error because one of the variables contains a , which is invalid for a float type:
Warning: A non-numeric value encountered ...
The number_format() method has the following method signature:
number_format(number,decimals,decimalpoint,separator).
By specifying the separator argument as '', this error could be fixed as follows:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2, '.', ''); //1147.42
$transactionfee = number_format(0.02 * $subtotal, 2, '.', ''); //131.13
$total = $subtotal + $vat + $transactionfee; // // 6556.7 + 1147.42 + 131.13 = 7835.25

Warning : A non-numeric value encountered & Fatal error : Uncaught DivisionByZeroError: Modulo by zero [duplicate]

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 ?
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.
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...
}
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared :)
I had this issue with my pagination forward and backward link .... simply set (int ) in front of the variable $Page+1 and it worked...
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> »</li>
<?php }
?>
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:\ampps\phpMyAdmin\libraries\DisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save's someone some trouble...
I encountered the issue in phpmyadmin with PHP 7.3. Thanks #coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably +, -, *, or /) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
You did not mean to use an operation that expects a scalar. For example, + (addition) when you meant . (concatenation).
You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
For example, if you have echo 3 + $variable and your $variable is the string "n/a", then you might decide to instead echo "not applicable". Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
Fix these warnings! In PHP 8, this becomes a fatal error: "Uncaught TypeError: Unsupported operand types".
PHP 8
Code that used to produce the warning "A non well formed numeric value encountered" in PHP 7.1-7.4 now gives this warning instead. This happens when you have a "trailing string", which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 + "30 meters";
Output:
Warning: A non-numeric value encountered in [...][...] on line X
33
Fix:
echo 3 + (float) "30 meters";
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
Solve this error on WordPress
Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694
Simple solution here!
locate a file of wp-includes\SimplePie\Parse\Date.php
find a line no. 694
you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
For others that answers here may not resolve the issue.
My issue didn't involve integers or concatenation.
My problem was a simple typo (an errant string in my code).
$conn = new PDO($details, $username, $password); -
Somehow I had entered a minus sign (-) in my code accidentally. Removing this fixed my issue. My guess is that PHP was erroring because since it saw the minus sign it expected it needed to perform some arithmetic there but there were no arguments.
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
It might be late but for those who still have been banging their head around like I was. In my case it was legacy project developed in PHP 5.6 but when I need to modify it I was running PHP 7.1. I didn't bother to change it.(Had to pay for it) So the issue is PHP 7.1 is more strict than PHP 5.6
In PHP 5.6 following is allowed.
$totalPrice = ' '
$someFoo = $totalPrice + 100
// This is totally fine. And PHP will not yell about it.
While in PHP 7.1 it will throw an error
$totalPrice = ' '
$someFoo = $totalPrice + 100
// Error : A non-numeric value encountered.
So after changing that line to $totalPrice = 0 everything worked.
Hope someone will find it useful.
Thank you everyone. I have had:
<?php echo $data['style_headerheight']-3; ?>
which gave the error:
PHP Warning: A non-numeric value encountered in framework/inc/customcss.php on line 78
To fix, I replaced that by:
<?php echo ((int)$data['style_headerheight']-(int)3); ?>
For me this happened right now because of the operator precedence. I wrote $something & BITMASK && $another_value and the binding of && was "tighter" than the one of &. Always make sure to use parentheses to avoid such problems!
Make sure that your column structure is INT.
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
I received this error after adding two formatted variables using the number_format() method. The reason is because this method usually formats your number with a , unless you specified the optional separator argument as null. For example, let's say I have the following code:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2); // 1,147.42
$transactionfee = number_format(0.02 * $subtotal, 2); // 131.13
$total = $subtotal + $vat + $transactionfee; // 6556.7 + 1,147.42 + 131.13 = ERROR
This would trigger the following error because one of the variables contains a , which is invalid for a float type:
Warning: A non-numeric value encountered ...
The number_format() method has the following method signature:
number_format(number,decimals,decimalpoint,separator).
By specifying the separator argument as '', this error could be fixed as follows:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2, '.', ''); //1147.42
$transactionfee = number_format(0.02 * $subtotal, 2, '.', ''); //131.13
$total = $subtotal + $vat + $transactionfee; // // 6556.7 + 1147.42 + 131.13 = 7835.25

PHP 7.2 getting Warning: A Non-Numeric Value Encountered with numeric and decimal value [duplicate]

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 ?
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.
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...
}
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared :)
I had this issue with my pagination forward and backward link .... simply set (int ) in front of the variable $Page+1 and it worked...
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> »</li>
<?php }
?>
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:\ampps\phpMyAdmin\libraries\DisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save's someone some trouble...
I encountered the issue in phpmyadmin with PHP 7.3. Thanks #coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably +, -, *, or /) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
You did not mean to use an operation that expects a scalar. For example, + (addition) when you meant . (concatenation).
You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
For example, if you have echo 3 + $variable and your $variable is the string "n/a", then you might decide to instead echo "not applicable". Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
Fix these warnings! In PHP 8, this becomes a fatal error: "Uncaught TypeError: Unsupported operand types".
PHP 8
Code that used to produce the warning "A non well formed numeric value encountered" in PHP 7.1-7.4 now gives this warning instead. This happens when you have a "trailing string", which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 + "30 meters";
Output:
Warning: A non-numeric value encountered in [...][...] on line X
33
Fix:
echo 3 + (float) "30 meters";
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
Solve this error on WordPress
Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694
Simple solution here!
locate a file of wp-includes\SimplePie\Parse\Date.php
find a line no. 694
you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
For others that answers here may not resolve the issue.
My issue didn't involve integers or concatenation.
My problem was a simple typo (an errant string in my code).
$conn = new PDO($details, $username, $password); -
Somehow I had entered a minus sign (-) in my code accidentally. Removing this fixed my issue. My guess is that PHP was erroring because since it saw the minus sign it expected it needed to perform some arithmetic there but there were no arguments.
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
It might be late but for those who still have been banging their head around like I was. In my case it was legacy project developed in PHP 5.6 but when I need to modify it I was running PHP 7.1. I didn't bother to change it.(Had to pay for it) So the issue is PHP 7.1 is more strict than PHP 5.6
In PHP 5.6 following is allowed.
$totalPrice = ' '
$someFoo = $totalPrice + 100
// This is totally fine. And PHP will not yell about it.
While in PHP 7.1 it will throw an error
$totalPrice = ' '
$someFoo = $totalPrice + 100
// Error : A non-numeric value encountered.
So after changing that line to $totalPrice = 0 everything worked.
Hope someone will find it useful.
Thank you everyone. I have had:
<?php echo $data['style_headerheight']-3; ?>
which gave the error:
PHP Warning: A non-numeric value encountered in framework/inc/customcss.php on line 78
To fix, I replaced that by:
<?php echo ((int)$data['style_headerheight']-(int)3); ?>
For me this happened right now because of the operator precedence. I wrote $something & BITMASK && $another_value and the binding of && was "tighter" than the one of &. Always make sure to use parentheses to avoid such problems!
Make sure that your column structure is INT.
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
I received this error after adding two formatted variables using the number_format() method. The reason is because this method usually formats your number with a , unless you specified the optional separator argument as null. For example, let's say I have the following code:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2); // 1,147.42
$transactionfee = number_format(0.02 * $subtotal, 2); // 131.13
$total = $subtotal + $vat + $transactionfee; // 6556.7 + 1,147.42 + 131.13 = ERROR
This would trigger the following error because one of the variables contains a , which is invalid for a float type:
Warning: A non-numeric value encountered ...
The number_format() method has the following method signature:
number_format(number,decimals,decimalpoint,separator).
By specifying the separator argument as '', this error could be fixed as follows:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2, '.', ''); //1147.42
$transactionfee = number_format(0.02 * $subtotal, 2, '.', ''); //131.13
$total = $subtotal + $vat + $transactionfee; // // 6556.7 + 1147.42 + 131.13 = 7835.25

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 ?
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.
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...
}
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared :)
I had this issue with my pagination forward and backward link .... simply set (int ) in front of the variable $Page+1 and it worked...
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> »</li>
<?php }
?>
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:\ampps\phpMyAdmin\libraries\DisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save's someone some trouble...
I encountered the issue in phpmyadmin with PHP 7.3. Thanks #coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably +, -, *, or /) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
You did not mean to use an operation that expects a scalar. For example, + (addition) when you meant . (concatenation).
You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
For example, if you have echo 3 + $variable and your $variable is the string "n/a", then you might decide to instead echo "not applicable". Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
Fix these warnings! In PHP 8, this becomes a fatal error: "Uncaught TypeError: Unsupported operand types".
PHP 8
Code that used to produce the warning "A non well formed numeric value encountered" in PHP 7.1-7.4 now gives this warning instead. This happens when you have a "trailing string", which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 + "30 meters";
Output:
Warning: A non-numeric value encountered in [...][...] on line X
33
Fix:
echo 3 + (float) "30 meters";
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here's the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
Solve this error on WordPress
Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694
Simple solution here!
locate a file of wp-includes\SimplePie\Parse\Date.php
find a line no. 694
you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
For others that answers here may not resolve the issue.
My issue didn't involve integers or concatenation.
My problem was a simple typo (an errant string in my code).
$conn = new PDO($details, $username, $password); -
Somehow I had entered a minus sign (-) in my code accidentally. Removing this fixed my issue. My guess is that PHP was erroring because since it saw the minus sign it expected it needed to perform some arithmetic there but there were no arguments.
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
It might be late but for those who still have been banging their head around like I was. In my case it was legacy project developed in PHP 5.6 but when I need to modify it I was running PHP 7.1. I didn't bother to change it.(Had to pay for it) So the issue is PHP 7.1 is more strict than PHP 5.6
In PHP 5.6 following is allowed.
$totalPrice = ' '
$someFoo = $totalPrice + 100
// This is totally fine. And PHP will not yell about it.
While in PHP 7.1 it will throw an error
$totalPrice = ' '
$someFoo = $totalPrice + 100
// Error : A non-numeric value encountered.
So after changing that line to $totalPrice = 0 everything worked.
Hope someone will find it useful.
Thank you everyone. I have had:
<?php echo $data['style_headerheight']-3; ?>
which gave the error:
PHP Warning: A non-numeric value encountered in framework/inc/customcss.php on line 78
To fix, I replaced that by:
<?php echo ((int)$data['style_headerheight']-(int)3); ?>
For me this happened right now because of the operator precedence. I wrote $something & BITMASK && $another_value and the binding of && was "tighter" than the one of &. Always make sure to use parentheses to avoid such problems!
Make sure that your column structure is INT.
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
I received this error after adding two formatted variables using the number_format() method. The reason is because this method usually formats your number with a , unless you specified the optional separator argument as null. For example, let's say I have the following code:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2); // 1,147.42
$transactionfee = number_format(0.02 * $subtotal, 2); // 131.13
$total = $subtotal + $vat + $transactionfee; // 6556.7 + 1,147.42 + 131.13 = ERROR
This would trigger the following error because one of the variables contains a , which is invalid for a float type:
Warning: A non-numeric value encountered ...
The number_format() method has the following method signature:
number_format(number,decimals,decimalpoint,separator).
By specifying the separator argument as '', this error could be fixed as follows:
$subtotal = 6556.7;
$vat = number_format(0.175 * $subtotal, 2, '.', ''); //1147.42
$transactionfee = number_format(0.02 * $subtotal, 2, '.', ''); //131.13
$total = $subtotal + $vat + $transactionfee; // // 6556.7 + 1147.42 + 131.13 = 7835.25

Categories