PHP - Repeat and append a variable to a calculation - php

I am trying to create a script that takes a $$variable and adds them to each other a number of times (based on another variable) - $total
This script is part of a much larger script that contains a few SQL queries and loops, hence the $$value as opposed to the usual $value
My current (static) script is like so:
$$value = ($$value + $$value + $$value + $$value + $$value);
This will work if I continue to modify the number of + $$value within the brackets but I need it to auto calculate and ammend itself so that it always writes the correct number of + $$value
I have tried using str_repeat() but it only fetches the first value of the $$value variable and then repeats that value (not grabbing the next value and so on). I have also tried creating a loop, which also didn't work.
I need something that will look at $total and from that number produce something similar to the following:
$$value = ($$value * $total)
The above will multiply the numeric value of the $$value and therefore not return the result I want.
Can anyone help?
Many thanks,
Tom
Pastebin Link to my script: http://pastebin.com/7Qg02hWB (in the pastebin, $$value is $$ob_id and $total is $o_total)

Not 100% sure what you mean, but how's
$foo = "";
for ($i = 0; $i < $total; $i++) $foo .= $$value;
$$value = $foo;
This will loop over $total times and concatenate it. If you're having problems like it's adding it as an integer for some reason you could always do a cast like (string) $$value. I know you said you tried a loop but we have no code so it could have been a problem with your code.

this?
perhaps you need powers?
$total = 5;
$$variable = 2; // random value; and why i have two 2 $$ ?
for($x=0;$x<$total;$x++) {
$$variable += $$variable;
}
echo $$variable;
OR,
$total = 5;
$$variable = 2;
echo "<br>POWER of 2^$total: ".pow($$variable,$total);

Related

For loop inside a function PHP

A total noob needs to do a math calculation in a for loop inside a function.
The closest I come is this, but it does not work of course.
function z1()
{
for ($x=1; $x<=11; $x++)
{
$z1=2/3+5*$x/(3-$x);
}
return $z1;
}
Any help or a solution would be appreciated
EDIT: FIXED
Needed to declare what to do if it is NaN or infinite
Not entirely sure what you're trying to do, but I'll make some assumptions.
In addition to a divide by zero error this gets, you are overwriting the value of $z1 each time the loop executes, so the value of $z1 once you return is whatever the final iteration of the loop assigned to $z1.
I think you may want to initialize the variable before the loop and use the += operator inside the loop, so the value of $z1 is incremented each time the loop iterates.
function z1() {
$z1 = 0;
for ($x = 1; $x <= 11; $x++) {
$z1 += 2 / 3 + 5 * $x / (3 - $x);
}
return $z1;
}

For loop not starting at 2, and consequently missing out the second field

I have a large form, which when submitted to the database, it needs splitting into odd and even (based on their HTML name), so I can perform a calculation on them.
There are 120 total HTML Input fields, so 60 odd and 60 even.
The for loops that iterates through them are:
$h=0; $o=0;
for($i=1; $i<=119; $i+=2)
{
$h = $h + Input::get($i);
}
for($i=2; $i<=120; $i+=2)
{
$o = $o + Input::get($i);
}
What I am finding is that the odd number for loop is working correctly, but even though the second loop begins at 2, it is skipping adding that Input::get($i); and moving onto the 4th input.
If I echo the odd for loop, it outputs (with all the input values at 1):
for($i=2; $i<=120; $i+=2)
{
echo $i;
echo (",");
$o = $o + Input::get($i);
echo (Input::get($i));
}
2,14,16,18,110,112,114,116,118,
So as you can see, it isn't picking up the '1' value from the 2nd input field.
Any help as to why this is would be greatly appreciated.
You do not need two loops to accomplish this, use the modulo math function to determine if there is a remainder of 0 when dividing by 2 (indicating an even number), try this out:
for($i=0; $i<=120; $i++)
{
if($i%2 == 0) //even
$o = $o + Input::get($i);
else //odd
$h = $h + Input::get($i);
}
You should make a single loop that iterates from 1 to 120. Then test if the counter is odd/even using the modulus operator ($a % $b).
i.e. if $a % 2 = 0 then the value is even else it is odd.

Add up numbers in a for each PHP?

I'm trying to add some numbers in a foreach loop in my PHP code. I am getting a percentage of numbers in a while loop in my MySQL query for each result that I get in my PHP page.
All I need to do is to add up the final values in and show them as total.
This is how I make up the percentage in my while loop in my MySQL query:
$percentage = 10;
$totalWidth = $fees;
$new_width = ($percentage / 100) * $totalWidth;
The $fees value is dynamic and it is different for each result in my while loop. the code above works as it should.
Now I want to add up all the values of $new_width. For example:
If one result's $new_width is 25 and the other one is 10 and another one is 5, I need to do this: $total = 25 + 10 + 5;
So I tried something like this:
$total = 0;
foreach($new_width as $var) {
$total = $var + $var;
}
echo $total;
but the above code doesn't really make sense and it won't do anything at all.
Could someone please advise on this matter?
First you want to change this line in your while loop so you get an array:
$new_width = ($percentage / 100) * $totalWidth;
to this:
//Declare it as an array before your while loop
$new_width = array();
//In your while loop
$new_width[] = ($percentage / 100) * $totalWidth;
//^^ See here
After this you just have to change the line in your foreach loop like this:
$total = $var + $var;
to this:
$total += $var;
(If you want you also can do this in your while loop)
If you have an array of numbers and you want to calculate the sum of those numbers, you should use array_sum().
According to the logic, you are setting the total to 2 X $var.
My answer is very similar, but you add it to the total which is outside of the loop and the value will keep growing:
$total = 0;
foreach($new_width as $var) {
$total += $var;
}
echo $total;
Or simply as stated before, if it is the only value in the array:
$total = array_sum($new_width);

Time it takes to assign a variable vs. assign + add

<?php
$a = microtime(true);
$num = 0;
for($i=0;$i<10000000;$i++)
{
$num = $i;
}
$b= microtime(true);
echo $b-$a;
?>
I run this on Ubuntu 12.10 and Apache 2
will give me approx. .50 seconds... when I run an assignment for a million times.. BUT BUT...
the same code, instead of $num = $i ... i go ...
$num = $i + 10; and it now takes almost 1.5 times less time to execute.. around .36 consistently..
How come the simple assignment is taking more, whilst an assignment and adding a 10 over it... takes less time!
I am by no means an expert, but here are my findings:
$s = microtime(true);
for($i=0;$i<100000000;$i++) $tmp = $i;
$t = microtime(true);
for($i=0;$i<100000000;$i++) $tmp = $i+10;
$u = microtime(true);
echo ($t-$s).chr(10).($u-$t);
Results in:
9.9528648853302
9.0821340084076
On the other hand, using a constant value for the assignment test:
$x = 0;
$s = microtime(true);
for($i=0;$i<100000000;$i++) $tmp = $x;
$t = microtime(true);
for($i=0;$i<100000000;$i++) $tmp = $x+10;
$u = microtime(true);
echo ($t-$s).chr(10).($u-$t);
Results in:
6.1365358829498
9.3231790065765
This leads me to believe that the answer has something to do with opcode cacheing. I honestly couldn't tell you what about it is making the difference, but as you can see using a constant value for the assignment makes a huge difference.
This is just an educated guess, based on looking at the latest php source on Github, but I'd say this difference is due to function call overhead in the interpreter source.
$tmp = $i;
compiles to a single opcode ASSIGN !2, !1;, which copies one named variable's value to another named variable. In the source, the key part looks like this:
if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) {
/* nothing to destroy */
ZVAL_COPY_VALUE(variable_ptr, value);
zendi_zval_copy_ctor(*variable_ptr);
}
$tmp = $i + 10;
compiles to two opcodes ADD ~8 !1, 10; ASSIGN !2, ~8;, which creates a temporary variable ~8 and assigns its value to a named variable. In the source, the key part looks like this:
if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) {
/* nothing to destroy */
ZVAL_COPY_VALUE(variable_ptr, value);
}
Notice that there's an extra function call to zendi_zval_copy_ctor() in the first case. That function performs some bookkeeping as needed (e.g. if the original variable is a resource, it needs to make sure that resource is not freed until this new variable is gone, etc.). For a primitive type such as a number, there's nothing to do, but the function call itself introduces some overhead, which accumulates over 10 million iterations of your test. You should note that this overhead is normally negligible, because even in 10 million iterations it only accumulated to .14 seconds.
#Kolink's observation about a constant being faster can also be answered in the same function. It includes a check to avoid redundant copying if the new value is the same as the old one:
if (EXPECTED(variable_ptr != value)) {
copy_value:
// the same code that handles `$tmp = $i` above
if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) {
/* nothing to destroy */
ZVAL_COPY_VALUE(variable_ptr, value);
zendi_zval_copy_ctor(*variable_ptr);
} else {
/* irrelevant to the question */
}
}
So only the first assignment of $tmp = $x copies the value of $x, the following ones see that the value of $tmp would not change and skip the copying, making it faster.

PHP negatives keep adding

I have this code here...
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + $row['total'];
}
What it does, it takes the values of total and adds them up...but when I have values that are negatives, it adds them up as well for an example when I have -51.75 and -17.85 I get -69.60 which it should be -33.90 how do I fix this?
`-33.901 is the value I am expecting because when its two negatives I would like to subtract, not add
Thanks,
J
This might help:
(-51.75) + (-17.85) = -69.60
(-51.75) - (-17.85) = -33.90
Assuming you always need to add the second number regardless of it's sign, you need to take the absolute value by using the PHP abs function with $row['total']:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + abs($row['total']);
}
In response to what you updated in your question:
-33.90 is the value I am expecting because when its two negatives I would like to subtract, not add
This is pretty much what using the abs function does. I could rewrite the above code snippet as:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row) {
if ($remaining >= 0) {
$remaining = $remaining + abs($row['total']);
}
else {
$remaining = $remaining - abs($row['total']);
}
}
However, this does the exact same thing as simply using the PHP abs function, since you are always adding the magnitude of $row['total'] to $remaining.
again --> see php's abs() function if you want to add things and ignore the sign.
I am not sure what your question is exactly, but this would keep adding the absolute values if $remaining is negative until it is positive again.
$remaining = $remaining + ($remaining < 0 && $row['remainingbalance']
< 0 ? -1 : 1) * $row['remainingbalance']);
This works for your example, it would be 0 - 51.75 + 17.85 = -33.9. But I am not sure if it's the behavior you want in the bigger picture.

Categories