warning a non-numeric value encountered in php [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
save data that an error occurred, but the data is still stored.
how do you get rid of these errors?
$query1 = "SELECT * FROM t_ref_pokja WHERE status='1' ORDER BY id";
$hasil1 = mysqli_query($koneksi,$query1);
if ($num_rows1 = mysqli_num_rows($hasil1)) {
while($list1 = mysqli_fetch_array($hasil1)){
$no = $list1['id'];
$a= "wisuda_$no";
$b= "RT_$no";
$c= "OPR_$no";
$d= "PI_$no";
$e= "Strat_$no";
$f= "pagu_$no";
$g= "save_$no";
$nama=$_POST[$f];
$wisuda1 = $_POST[$a];
$wisuda = str_replace(",", "",$wisuda1);
$rt1 = $_POST[$b];
$rt = str_replace(",", "",$rt1);
$opr1 = $_POST[$c];
$opr = str_replace(",", "",$opr1);
$pi1 = $_POST[$d];
$pi = str_replace(",", "",$pi1);
$strat1 = $_POST[$e];
$strat = str_replace(",", "",$strat1);
$save = $_POST[$g]; //line 66
$total =($wisuda+$rt+$opr+$pi+$strat); //line 67
$tahun = date("Y");
if($save == "save"){
enter image description here
please help me

First, these are notices and warnings rather than errors. As you have seen, code execution will continue in these scenarios whereas script execution would terminate in case of an error.
There are at least two different issues here:
You are accessing an array index that does not exist(line 66)
You are using arithmetic operators on non-numeric values(line 67)
For 1, you should check that the key exists in the $_POST array before accessing it. I am assuming since it is absent in the request, the "save" parameter is optional. Since it is not present, null will be assigned to $save, so presumably this is the desired value for later logic. You can simply add a condition using array_key_exists or isset to prevent the notice. If you are you using php 7 or later you can use the "null coalesce" operator(??).
$save = array_key_exists($g, $_POST)?$_POST[$g]:null;
OR
$save = $_POST[$g]??null;
For 2, I would need more information about the values and intentions thereof. Judging by the addition operator and comma replacement, it appears that you are accepting numeric values that are formatted in some way. PHP will implicitly convert numeric strings to numbers in cases such as this. You may need to remove further formatting. Perhaps intval or floatval would be applicable depending on the input data. Ultimately, you need to extract the numbers that you need from the strings and convert them to numeric values before performing addition(unless you are attempting string concatenation, in which case see the . operator)

Related

Unusual string collision in PHP [duplicate]

This question already has answers here:
PHP in_array() / array_search() odd behaviour
(2 answers)
Closed 4 months ago.
I have an array of lower case hex strings. For some reason, in_array is finding matches where none exist:
$x = '000e286592';
$y = '0e06452425';
$testarray = [];
$testarray[] = $x;
if (in_array($y, $testarray)) {
echo "Array element ".$y." already exists in text array ";
}
print_r($testarray);exit();
The in_array comes back as true, as if '0e06452425' is already in the array. Which it is not. Why does this happen and how do I stop it from happening?
Odd. This has something to do with the way that PHP compares the values in "non-strict" mode; passing the third argument (strict) as true no longer results in a false positive:
if (in_array($y, $testarray, true)) {
echo "Array element ".$y." already exists in text array ";
}
I'm still trying to figure out why, technically speaking, this doesn't work without strict checking enabled.
You can pass a boolean as third parameter to in_array() to enable PHP strict comparison instead of the default loose comparison.
Try this code
$x = '000e286592';
$y = '0e06452425';
$testarray = [];
$testarray[] = $x;
if (in_array($y, $testarray, true)) {
echo "Array element ".$y." already exists in text array ";
}
print_r($testarray);exit();

PHP Why does explicit typecast + 1 work, but not with an increment operator

Firstly, let's say for the sake of argument, the reasons why I want to do this is arbitrary and not solution specific.
I would like to explicitly cast a variable, regardless of input, and increment it after typecasting, not with the original variable. For example, not like this:
$num = "47 downvotes";
(int) ++$num;
I am looking for something similar to this psuedo-coded version, or a variation thereof:
$num = "value";
++((int) $num);
For PHP being loose, I was really hoping this to work, but I can't use the Pre-increment operator without creating another variable first.
$num = "value";
$cast = (int) $num;
echo ++$cast;
While testing, I found that PHP is loose enough for it to work by adding a digit however:
$num = "47 dogs";
echo ((int) $num) + 1;
I also understand my first example, isn't wrong, but again, for arbitrary reasons, I need to make sure it has been casted prior to incrementing/decrementing.
So the question is, why is PHP loose enough for the latter to compile?
If you could provide resources or links to any reputable reading material I would appreciate that as well.
With explicit typecasting you have to assign the result to a variable. In your examples, you are trying to increment variables when they are strings, which fails or doesn't produce the result you expect in combination with typecasting.
Look at your original example:
<?php
$num = "47 downvotes";
echo $num . PHP_EOL;
echo ++$num;
The result of incrementing a string isn't what you expect it to be:
47 downvotes
47 downvotet
So your original supposition is that PHP doesn't work when in fact it does.
$num = "47 downvotes";
echo (int) ++$num . PHP_EOL;
$num2 = "47";
echo (int) ++$num2;
Output:
47
48
The process of typecasting is inherently complicated, and has all sorts of behavior that can produce unexpected results, and just isn't the catchall dependable "fix your input" that will let you find the numeric portion of any string available to you in a single line of code, but that doesn't mean that PHP is flawed.

.= syntax php undefined variable [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
I got this error message
Undefined variable: x in ../../../../.php on line 35
I get the error on this line.
$x .= $y->getContent();
This line of code is in a foreach loop.
How do I get rid of the error message.
If I replace the .= with just = I'm not getting the correct output.
I hope I provided enough information
And what does .= do?
Thanks in advance.
.= is used (in your code) to concatenate the value of $x with result of ->getContent() call on $y and write the result back into $x.
Is like write $x = $x.$y
Of course if $x does not exists (like in your example I suppose; with "not exists" I mean that hasn't a value), regardless how you wrote your expression, this will fail. Moreover, $x and $y will be considerated strings so, please pay attention to your variables type (you can't concatenate two object, for example)
$x.=$y is a shortcut for $x=$x.$y
so if $x = 'cat' and $y = 'fish' then the result of $x.=$y is 'catfish'
As to your error, you need to create the variable $x 1st, out side the loop:
$x='';
foreach($var as $y){
$x.=$y;
}
$x = '';
foreach()
{
$x .= $y->getContent();
}
*it is must to define $x becouse you are append value in $x *
Define x before your loop :
$x = '';
The .= operator is a string operator to concatenate strings.
$x .= $yis the same as $x = $x.$y
You could read about string operator
s in the official PHP reference
If $x don't exist you can't concatenate it with $y, this is the reason of the error message.

Weird PHP String Integer Comparison and Conversion

I was working on some data parsing code while I came across the following.
$line = "100 something is amazingly cool";
$key = 100;
var_dump($line == $key);
Well most of us would expect the dump to produce a false, but to my surprise the dump was a true!
I do understand that in PHP there is type conversion like that:
$x = 5 + "10 is a cool number"; // as documented on PHP manual
var_dump($x); // int(15) as documented.
But why does a comparison like how I mentioned in the first example converts my string to integer instead of converting the integer to string.
I do understand that you can do a === strict-comparison to my example, but I just want to know:
Is there any part of the PHP documentation mentioning on this behaviour?
Can anyone give an explanation why is happening in PHP?
How can programmers prevent such problem?
If I recal correcly PHP 'casts' the two variables to lowest possible type.
They call it type juggling.
try: var_dump("something" == 0);
for example, that'll give you true . . had that bite me once before.
More info: http://php.net/manual/en/language.operators.comparison.php
I know this is already answered and accepted, but I wanted to add something that may help others who find this via search.
I had this same problem when I was comparing a post array vs. keys in a PHP array where in my post array, I had an extra string value.
$_POST["bar"] = array("other");
$foo = array(array("name"=>"foobar"));
foreach($foo as $key=>$data){
$foo[$key]["bar"]="0";
foreach($_POST["bar"] as $bar){
if($bar==$key){
$foo[$key]["bar"]="1";
}
}
}
From this you would think that at the end $foo[0]["bar"] would be equal to "0" but what was happening is that when $key = int 0 was loosely compared against $bar = string "other" the result was true to fix this, I strictly compared, but then needed to convert the $key = int 0 into a $key = string "0" for when the POST array was defined as array("other","0"); The following worked:
$_POST["bar"] = array("other");
$foo = array(array("name"=>"foobar"));
foreach($foo as $key=>$data){
$foo[$key]["bar"]="0";
foreach($_POST["bar"] as $bar){
if($bar==="$key"){
$foo[$key]["bar"]="1";
}
}
}
The result was $foo[0]["bar"]="1" if "0" was in the POST bar array and $foo[0]["bar"]="0" if "0" was not in the POST bar array.
Remember that when comparing variables that your variables may not being compared as you think due to PHP's loose variable typing.

Strange PHP array behaviour [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP String in Array Only Returns First Character
I've got following problem. When I run script below I got string(1) "F" as an output. How is that possible? No error, notice displayed.. nothing. Key whatever doesn't exist in $c. Can you explain that?
<?php
$c = 'FEEDBACK_REGISTER_ACTIVATION_COMPLETED_MSG';
var_dump ($c['whatever']);
?>
I'm having this issue on PHP 5.3.3. (LINUX)
PHP lets you index on strings:
$str = "Hello, world!";
echo $str[0]; // H
echo $str[3]; // l
PHP also converts strings to integers implicitly, but when it fails, uses zero:
$str = "1";
echo $str + 1; // 2
$str = "invalid";
echo $str + 1; // 1
So what it's trying to do is index on the string, but the index is not an integer, so it tries to convert the string to an integer, yielding zero, and then it's accessing the first character of the string, which happens to be F.
Through Magic type casting of PHP when an associative array can not find the index, index itself is converted to int 0 and hence it is like
if
$sample = 'Sample';
$sample['anystring'] = $sample[0];
so if o/p is 'S';

Categories