PHP non-numeric value warning - php

I'm getting the following error:
Warning: A non-numeric value encountered
Does anyone have the solution? (I'm a beginner.)
EDIT:
Here is the code:
while($r = mysqli_fetch_row($result))
{
$items[] = $r;
}
$itemArray = array($items[0][0]=>array('Proid' => $items[0][0],
'name'=>$items[0][1], 'brand'=>$items[0][2], 'desc'=>$items[0][3],
'quan'=>$_POST["quantity"], 'price'=>$items[0][4], 'image'=> $items[0][5]));
$_SESSION['cart'] += $itemArray;
$i = $item['Proid'];
$tp = $item['quan'] * $item['price'];
$tp2 += $tp;

Probably some of your values are a string, not a integer or float.
To make sure, use
intval() to convert a string to integer
or
floatval() to convert a string to float.
This is just a warning, php will try to convert it behind the scenes, but if may not be accurate, for example, if you use , as decimal separator, or if you use some thousand separator.

Not sure which PHP version you are using but a Warning will be emitted if a non-numeric value is encountered. See this link.
so what you can do is before doing calculation make sure you check if the entity is numeric or not and for that you can use is_numeric() PHP function.
For example in your case :
if(is_numeric($item['quan']) && is_numeric($item['price'])){
$tp = $item['quan'] * $item['price'];
}

Related

My php function doesn't work - integer to string conversion issues

This is my php function it must return "5" but it returns nothing.
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers=456789;
echo get_second($numbers);
?>
When I tried out this code, this returns nothing (NULL, empty).
But I tried out this function below, worked perfectly.
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers=$_POST['number_input'];//that includes numbers
echo get_second($numbers);
?>
This code returns me second number of the post data. What I must do to work my First function? What is the difference between first $numbers variable and second $numbers variable?
Here the problem has to be better defined: how to get the second digit from a number. Your initial approach was correct in logic, but incorrect in the assumption that a number is a order set of characters. Only strings are ordered set of characters. Once you transform the integer 45678 to the string 45678 you can easily intercept the second character by using substr or even directly the string - because in PHP strings can be treated as arrays of characters.
#RamRaider solution is better than other have suggested but is overkill to use preg_split. Other solutions ask you to modify the type of the variable which is not done by adding quotes, but is done by casting to string, which is simpler and faster than a regular expression and you maintain your original variable in original form and your original function definition.
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers = 456789;
// casting to string
echo get_second((string)$numbers);
// or transform to string by concatenation to a string
echo get_second($numbers ."");
// even quoting works
echo get_second("$numbers");
// using strval
echo get_second(strval($numbers));
// using settype
echo get_second(settype($numbers, "string"));
Try this: (add quotes to your integer variable)
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers="456789";
echo get_second($numbers);
?>
If you want to get Character by its number then you can use substr()
function get_second($num)
{
return substr($num,1,1);
}
$numbers="456789";
echo get_second($numbers);
you are declaring a number in the $number variable.
if you want to view the second element than you have to use string.
try
$numbers= "456789";
it will output 5.
You could use preg_split to force an array from which you can choose any number by index, like:
$number=12358397;
function get_number($num,$i){
$num=preg_split( '#^\d$#', $num );
return $num[0][$i];
}
echo ' [1] > > > ' . get_number($number,1);

array_multisort Converts string index into an integer index

I have two arrays:
$info = array();
$submitted = array();
I declared an assignment below:
$info['idnumber'] = 10066;
$submitted[$info['idnumber']] = 'Wow';
array_multisort($submitted);
After doing so, displayed $submitted array.
foreach($submitted as $key => $row){
echo $key;
}
Why does it display 0 instead of 10066? I tried tweaking my code to:
$info['idnumber'] = 10066;
$submitted[(string)$info['idnumber']] = 'Wow';
or
$info['idnumber'] = 10066;
$submitted[strval($info['idnumber'])] = 'Wow';
Still it displays 0. What shall I do to display 10066 as the index of the $submitted array?
Update:
I found out it's a known bug of array_multisort, but still it has no solutions. Any idea how to fix ]it?
As you pointed out it is a known behaviour.
The solution was proposed in the discussion
For the moment I'm going to say prefix all your array keys with an extra 0 (or any non-numeric) to force their casting as strings.
When you try to cast integer into string like this:
(string)$info['idnumber']
you still get the integer, because you have a valid number as a string.
So you need to have a string as with some prefix. Prefix can be a 0 or any other non-numeric character. like an i
$info['idnumber'] = '010066';
Or
$info['idnumber'] = 'i00066';
This will return the exact index.

PHP: If number (with comma), convert it to right number format (with point)

I have an array of mixed values:
$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54'); -1,94 -1,55
As you can see it contains text and both negative and positive comma-numbers.
I need to convert the numeric values to the right number format and leave the text values as is.
Now I'm looping over the values:
foreach ($row as $value) {
// If $value is numeric, convert it to the
// right number format for use with MySQL (decimal(10,2))
// If not, leave it be.
}
Two related questions I've investigated but cannot find a suitable solution.
Converting a number with comma as decimal point to float
I need php regular expression for numeric value including "-" and ","
Could anyone provide a practical example?
You don't need to use regular expressions.
use str_replace() as you need to replace the ',' for a '.', and then use intval() or floatval() functions to get the numeric value. You can also use strstr() to look for the '.' and decide if using intval() or floatval()
Example:
$row = array('Unspecified risk', 'Yes', '8', '3', '2', '13', 'none', '-1,49', '-2,51', '-1,46', '-1,54');
function toNumber($target){
$switched = str_replace(',', '.', $target);
if(is_numeric($target)){
return intval($target);
}elseif(is_numeric($switched)){
return floatval($switched);
} else {
return $target;
}
}
$row = array_map('toNumber', $row);
var_dump($row);
We use str_replace() to replace the dot for the comma, this way it's a international notation float, even if it's on string, this way later on we can check if it's numeric with is_numeric() <-- this function is awesome as it detects from a string if it's a number or not, no matter integer or float etc.
We use the is_numeric to check if the value is integer float or text and return the corresponding value using intval() or floatval() (the value without the replace applied will not return as a valid numeric, only after switching the , and . it will return true as numeric).
We use $row = array_map('toNumber', $row); to apply the changes to the array.
Profit xD
$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54');
foreach($row as $key => $var) {
if(strstr($var, ",") && !is_numeric($var)) {
$var1 = str_replace(",","", $var);
if(is_numeric($var1)) {
$decimal = strstr($var, ',', TRUE);
$digits = str_replace($decimal, "", $var1);
$finalValue = $digits * pow(10,$decimal);
$row[$key] = $finalValue;
}
}
}
echo "<pre>"; print_r($row);
NOTE: This will work for php 5.3 or php 5.3+
I am responding so many years later because I dont find any of the provided solutions reliable enough.
This is a more rigid test if a string contains a float with a comma as decimal separator, and if yes, converts it. Also it removes spaces around the number if needed. It does not really test for malformed numbers.
if( preg_match('/^\s*[0-9\.]*,\d*\s*$/', $str))
return (float)str_replace(",",".",str_replace(".","",trim($str)));
else
return $str ;
If you know a numerical value ALWAYS has a European notation (so 1.234 without a comma should also be coverted to 1234), it should be:
if( preg_match('/^\s*[0-9\.]*,?\d*\s*$/', $str))
return (float)str_replace(",",".",str_replace(".","",trim($str)));
else
return $str ;
If you want a truly rigid test, no malformed numbers (like starting with a thousands separator), and that uses ONLY three digits between thousands separators (not all countries use three, though, like India!):
if( preg_match('/^\s*\d{0,3}((?<=\d)\.\d{3})*,?\d*\s*$/', $str))
return (float)str_replace(",",".",str_replace(".","",trim($str)));
else
return $str ;
And lastly if you want to go even more rigid and also do not want numbers to be able to begin or end with a comma ("1.234," or ",17", which in some cases are considered correct) it becomes
if( preg_match('/^\s*\d{1,3}((?<=\d)\.\d{3})*(,\d+)*\s*$/', $str))
return (float)str_replace(",",".",str_replace(".","",trim($str)));
else
return $str ;
Use is_numeric to test and number_format to format:
foreach ($row as &$value) {
$number = str_replace(',', '.', $value);
if (is_numeric($number)) {
$value = number_format($number, 2, '.', '');
}
}
unset($value);

Check if cast to int will lose data - PHP

I have this piece of code:
$result = new stdClass();
foreach ($array as $index => $value) {
if(is_numeric($value)){
$int = (int)$value;
$double = (double)$value;
if($int == $double)
$value = $int;
else
$value = $double;
}
$index = strtolower($index);
$result->$index = $value;
}
And it worked for ages. Now I got a problem with it. I have a column in my database that has numbers (big numbers) in it. But they're not numbers, they're varchar and those numbers are not for mathematical purpose. Unfortunately, since the column is fully filled with numbers only, it passes the is_numeric test, but since it's a giant number, it loses data due to memory limitation (4 billions, I think).
Anyway, how can I check if after the cast I lost data or not to my variable?
Thanks.
if($value<=PHP_INT_MAX) ... // safe to convert
else // not safe
Convert it back and see if it gives the same value as the source.

PHP - Summing an array of decimal values

I'm trying to calculate the sum of an array of decimal values in PHP, but for some reason it keeps rounding to integers.
for example:
$oldArray = array(0.00,1000.11,988.92,978.22,964.01,953.07,948.82,917.26,902.56,913.21,904.08,898.86,892.79);
$myVar = 0.0;
for($k=1;$k<10;$k++)
{
$myVar += $oldArray[$k];
}
print_r($myVar);
$oldArray is actually populated with decimal values from an SQL query (the length of $oldarray is about several hundred, but I want the first 10.
In the above example, I'm expecting $myVar to be a decimal, but it turns out to be just an integer. I tried setting $myVar = 0.0000 before the for loop, I tried $myVar += $oldArray[$k] + 0.0000, etc but nothing seems to work.
What am I doing wrong? How do I explicitly set $myVar to be a decimal?
Given that this seems impossible to reproduce, to me it sounds like a problem with your PHP environment itself.
Check php.ini for a setting called "precision", and make sure it's set to the default of 14 significant figures. I can't imagine why this would be changed, but it would definitely have an impact.
You can try using array_sum() instead and use (float) to cast the values. Additionally I would make sure that the values in the array are in the correct format (1.45 and not 1,45). HTH.
Update
Btw. you can use "is_float()" to check every parameter in the array.
Can't reproduce this.
php > $oldArray = array(0, .1, .2, .3, .4, .5, .6, .7, .8, .9);
php > $myVar = 0.0;
php > for($k=0;$k < count($oldArray);$k++)
php > {
php { $myVar += $oldArray[$k];
php { }
php > print_r($myVar);
4.5
EDIT: I tried the code in your comment, and it's fine. Like AlbertoPL, I suspect the problem is elsewhere.
php > $oldArray = array(0.01,1000.11,988.92,978.22,964.01,953.07,948.82,917.26,902.56,913.21,904.08,898.86,892.79);
php > $myVar = 0.0000;
php > for($k=1;$k<10;$k++)
php > $myVar += $oldArray[$k];
php > print_r($myVar);
8566.18
Make your own implementation:
function sum_array($arr){
$count = 0;
foreach ($arr as $val){
if (!is_numeric($val) // neglect any non numeric values
{
$error = true;
continue;
}
else{
$count = $count + ($val*1); //casting to numeric if the value supplied as string
}
}
return $count
}
echo sum_array($myArray);

Categories