PHP errror in cos() function - php

In an exercise I did :
<?php
$initial = '555';
$a = octdec($initial);
echo $a . "\n";
$b = deg2rad($a) . "\n";
echo $b;
$c = cos($b). "\n"; *(line 9)*
echo $c;
and it does show the correct answer, as well as an error:
365
6.3704517697793
0.99619469809175
PHP Notice: A non well formed numeric value encountered in /home/ccuser/workspace/hg2pmf/index.php on line 9
if I change line 9 with : $c = cos(6.3704517697793). "\n"; the message of error disappear. Why can't I use the $ inside the cos() when in deg2rad() works perfectly?

The problem is that on this line...
$b = deg2rad($a) . "\n";
You are adding the new line onto the end of the calculated value.
So remove it and your value will be the number you expect...
$b = deg2rad($a);
As a help, I use
declare(strict_types=1);
and I get the error...
Fatal error: Uncaught TypeError: cos(): Argument #1 ($num) must be of
type float, string given in
which shows how it's changed the value from a number to a string.

Related

"A non numeric value encountered" on a line with just a number [duplicate]

This question already has an answer here:
A non-numeric value encountered
(1 answer)
Closed 1 year ago.
I don't know what I changed but suddenly I'm getting an error on the code that worked before:
Warning: A non-numeric value encountered in C:\xampp\htdocs.apps\DeSplinterRekenen\Code\addAnswer.php on line 32
These are line 31, 32 and 33, I put the 1 in a seperate line to point out that the error is actually pointed on the 1:
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . $_SESSION['activeQuestion'] +
1
);
Why is php saying a literal 1 is non-numeric?
I've tried this and it worked, but it just seems weird I have to do it this way:
$var = $_SESSION['activeQuestion'] + 1;
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . $var);
exit();
+ and . have the same precedence, and they're left-associative. So ($a . $b + $c) is equivalent to ($a . $b) + $c, not $a . ($b + $c).
In your case, the concatenations don't produce a number, so when you try to add 1 to it, you get an error. You can use parentheses to specify the desired grouping.
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . ($_SESSION['activeQuestion'] + 1));

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

Failed to parse time string: it is working good on my local but on server

I have a code which is working on my localhost but in server it throws error.
the error is: Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (#1645.0000000006) at position 14 (0): Unexpected character
my code is:
function secondsToTime($seconds)
{
$arr = array();
$dtF = new DateTime('#0');
$dtT = new DateTime("#$seconds");
$arr[0] = $dtF->diff($dtT)->format('%h');
$arr[1] = $dtF->diff($dtT)->format('%i');
$arr[2] = $dtF->diff($dtT)->format('%s');
return $arr;
}
print_r(secondsToTime("1645.0000000006"));
what is the problem? thanks everyone
Apparently handling of microseconds changed around PHP 7.1 and PHP accepts decimal values as valid timestamps starting with that version, but not before. If you have to make it compatible with previous versions, you need to cast your float to an int:
$dtT = new DateTime('#' . (int)$seconds);

send parameters from php to c++

I want to send some string parameter to a cpp.exe from PHP thanks to exec function. The aim of the exe is to compute a rank of documents according to a query.
Here is the code in php :
$query = "is strong";
$file = "vsm.exe $query";
exec($file,$out);
echo $out[0];`
I received this output for echo $out[0];
Notice: Undefined offset: 0 in C:\xampp\htdocs\analysis.php on line 25
But, my vsm.exe only work (meaning I receive my ranks in the $out variable as a string which is okay) when the query is without space:
$query = "is";
$file = "vsm.exe $query";
exec($file,$out);
echo $out[0];
I followed that example which works with integer parameter (this is not what I want, I want to send sentences):
$a = 2;
$b = 5;
exec("tryphp.exe $a $b",$c_output);
echo $c_output[0];
$c_array0 = explode(" ",$c_output[0]);
echo "Output: " . ($c_array0[0] + 1);
echo "Output: " . ($c_output[0] + 1);
How could I send strings including spaces (could be long text) as parameters to c++?
Thanks in advance.
I actually find something but still not enough good:
$query = "is strong";
$file = 'vsm.exe "is strong"';
exec($file,$out);
echo $out[0];
It returns me the rank I wanted. However, I look for a way to use $query as a parameter, not directly the string "is strong".

PHP Notice: String offset cast occurred line 251 & 258

i get php notice with this
$code = "";
while ($id > $length - 1) {
// determine the value of the next higher character
// in the short code should be and prepend
$code = self::$chars[fmod($id, $length)] . $code; //<-- line 251
// reset $id to remaining value to be converted
$id = floor($id / $length);
}
// remaining value of $id is less than the length of
// self::$chars
$code = self::$chars[$id] . $code; //<-- line 258
return $code;
The NOTICE code is this part:
$code = self::$chars[fmod($id, $length)] . $code;
$code = self::$chars[$id] . $code;
How to fix it? I can’t find it, please your help all.. :)
Using intval should fix it:
..$chars[intval(fmod($id, $length))]..
That is caused because fmod returns a float, and it casts it to integer. See this example:
$a = 'abcdef';
$b = $a[1.0];
echo $b;
And the output:
E_NOTICE : type 8 -- String offset cast occurred -- at line 3
b
If you think about it (at least in this case), you can either be at position 1, or at position 2, for example. You can't be at position 1,5. So when you try to access something float, it automatically casts the value to integer and lets you know that it did that.

Categories