PHP is concatenating instead of adding - php

I'm having this problem where my PHP code is concatenating instead of adding
$offset=$_POST['offset']; //Get the offset
$searchLimit = 10;
$searchCount = count(sql) //For the purpose of this question, it returns the result count
Now I want to calculate the 'from' display for pagination, so I do
$from = ($offset*$searchLimit)+1;
It works fine when
$offset == 0
I get the expected result which is 1. But when
$offset == 1
It gives me 101. Basically it is concatenating the 10 and 1 to give me 101. I've tried the following
$from = (int)($offset*$searchLimit)+1
$from = ((int)($offset)*$searchLimit)+1
$from = (((int)($offset)*$searchLimit)+1)
I even tried
$offset = (int)$_POST['offset'];
But all of them are giving the same result.

You are missing a $ before searchLimit. As a result, it is being treated as a string. This result in unexpected behaviour.

You missed a $ sign before searchLimit (and perhaps before sql). -_-

Related

Psalm reports InvalidArrayOffset, but the value will be within bounds

When running Psalm on this simple "random string" generator:
$letters = 'abcdefghjklmnpqrstuvwxyz';
$numbers = '23456789';
$number_count = \strlen($numbers);
$letter_count = \strlen($letters);
$pass = '';
while (\strlen($pass) < 9) {
$pass .= $letters[\random_int(0, $letter_count - 1)];
}
while (\strlen($pass) < 12) {
$pass .= $numbers[\random_int(0, $number_count - 1)];
}
I get an error (as seen here):
ERROR: InvalidArrayOffset - 15:11 - Cannot access value on variable $numbers using a int offset, expecting -8|-7|-6|-5|-4|-3|-2|-1|0|1|2|3|4|5|6|7
What I don't understand, is what I get the error on line 11, and not 4 lines earlier, when I'm fetching characters from $letters.
I'm doing exactly the same both times, yet on the second one it seems psalm can't infer the possible return values from random_int(), and that they will be within acceptable values. And yet it can the first time.
What I'm doing wrong, and how can I make Psalm understand the code?
I know that the code works, but I am confused why the first $pass assignment does not trigger an error, but the second one does.
The code is fine. The issue described here is tracked at https://github.com/vimeo/psalm/issues/5458.

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

show number to 100 decimal places

As an example I have code similar to this:
$r1 = 7.39999999999999;
$r2 = 10000;
echo bcmul($r1,$r2,100);
//returns 74000.0
echo ($r1*$r2);
//returns 74000.0
I am wanting it to return 73999.9999999999 rather than rounding it off.
Is there a formula or function to do this?
The doc http://php.net/manual/de/function.bcmul.php says:
left_operand: The left operand, as a string.
right_operand: The right operand, as a string.
So use strings instead:
$r1 = "7.39999999999999";
$r2 = "10000";
echo bcmul($r1,$r2,100);
works.
Or if you have these varibales from somewhere cast them (via (string) ) to string. Maybe at this step you could encounter some roundings already...
I'm not a php person, but a quick Google suggests you may want the
$number_format()
function and specify the $decimals parameter. See this link

Divide money value for payment (PHP)

First I thought this was a stupid question, and i should do some search and it would be easy to solve. But I am afraid I just ain't getting anywhere!
The thing i need to do is simple. I have a U$ value and i want to divide it by 12. Thats it.
Well, the thing is that this value is outputed by a function, and echoes ok, look:
<?php
$preconormal = wpsc_the_product_price(); // it echoes like 99.90
$precoja = str_replace (".", "", $preconormal);
echo $precoja; //echo ok -> 9990
$quantas = '12';
$parcela = $precoja/$quantas; // ok, so divide 9990 by 12, right?
echo $parcela; //no!!!!! it echoes 0 :(
?>
I really hope you can help me!
You are trying to divide strings, if you used numbers say
$quantas = 12;
$precoja = 9990;
What happens?
It should fix the division, in which case, prior to the mathmematics, convert your vars to integs by
$quantas = intval($quantas);
$precoja = intval($precoja);
//your manipulation here..l
Remove the quotes...
$quantas = '12';
to
$quantas = 12;
$precoja = floatval($preconormal)*100;
$preconormal = $precoja / 12;
I'd change your 5th line by removing the single quotes and/or 6th line with $parcela = (int)$precoja / (int)$quantas; because as soon as you use the function str_replace then $precoja becomes a string. Also having the single quotes earlier on = '12' it is also a string and that division returns 0.

PHP: Max and Min returning incorrect results

I am sure this is because of the "g" on the end but this is the scenario and results when I try and work out a ratio percent. I always want to divide the highest of 2 numbers by the lowest.
$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"
$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"
PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"
It's type casting;
$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
result will be 175%
When you want to use your strings in mathematical operations, and you know that the unit is placed at the end as it is in your example, you can cast your variables to floats:
$item1_numeric = (float) $item1;
But obviously it is better to have the values and the units separated in your variables / database.
Use: substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.
You can't compare 2 strings with round().
Edit : If $item1 = "200g", ma solution is ok, but if if $item1 = "200.00g" you need to remove "." before round() with for example pregreplace.
Oh, YAPHPB - and one of my favorite ones. Even though it's written in the Doc:
When [max()] given a string it will be cast as an integer when comparing.
... it's only a partial truth: if at least one of compared values is a number, or a numeric string.
Otherwise all the strings will be compared as strings: first {0} characters of each strings will be compared, then {1}, then {2}... etc.
So basically that's what happens here:
echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
echo max("200.00g", 50); // "200.00g", as it gets converted to int (become 200)
And that's even more crazy:
echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
echo max("200.00", "1000.00"); // "1000.00", as we tried to help you, no, really!
The latter result can actually be predicted by someone knowing of numeric concept: when both strings are pure numbers, they got converted to numbers when compared. Still, I found this behavior unreliable, to say the least.
The bottom line: if you need to compare numbers, compare numbers, period. Type conversion in PHP can get real messy - and bite you in the bottom real hard when you least expect it. )

Categories