I have two variables:
$low = 0;
$high = 100;
Using these two variables, I want to set 4 new variables, starting from the low value going to the high. So in this case, it would be:
$low = 0;
$value_1 = 20;
$value_2 = 40;
$value_3 = 60;
$value_4 = 80;
$high = 100;
What calculation can I do to achieve this? The $low
and $high
values were set just to help explain my question. These two values are set by the user.
If I understand correctly you want the distance between $low and $high to be equally distributed between four values.
I think the algorithm is pretty self explanatory in the code below...
<?php
$low = 0; //substitute user entry
$high = 100; //substitute user entry
$difference = $high - $low;
$increment = $difference/5;
//we use 5 because we need four divisible values, you can change this
//based on how many incremental values you want.
$step = $low;
echo $low."<br>";
for($x=0;$x<4;$x++)
{
$step+=$increment;
echo $step."<br>";
}
echo $high."<br>";
?>
For $low = 0, $high = 100
- this will print:
0
20
40
60
80
100
For $low = 57, $high = 94
- this will print:
57
64.4
71.8
79.2
86.6
94
For $low =222, $high = 1000
- this will print:
222
377.6
533.2
688.8
844.4
1000
You can round()
as you need. Also make sure that you do basic validation for $low and $high, for eg, that $low is actually smaller than $high etc.
After reading your updates, maybe range is enough for your needs:
$low = 0; $high = 100; $steps = 5;
$value = range($low, $high, ($high-$low)/$steps);
print_r($value);
Array ( [0] => 0 1 => 20 2 => 40 [3] => 60 [4] => 80 [5] => 100 )
See test at eval.in (link expires soon)
Just run a loop and create a variable. Use the code below
<?php
$low = 0;
$high = 100;
$step = 20;
$f = 0;
for($i=$low; $i<=$high; $i+=$step){
${"variable_$f"} = $i;
$f++;
}
echo $variable_1;
Hope this helps you.
You can use a for loop to make an array $low
, &high
and $step
can have any value
$low = 0;
$high = 100;
$step = 20;
$var = array();
for($x = 0; $x < $high/$step; $x++) {
if($x == $low || $x == $high) {
continue;
} else {
$var[$x] = $x * $step;
}
}
The array will look like
Array ( [1] => 20 [2] => 40 [3] => 60 [4] => 80 )
I would subtract $high from $low and then devided by number of varibles I want to have. Example:
$low = 50; $high = 1498;
I want to create 4 variables.
($high - $low) / 4 = 362
Now I know the $step and I can do the for loop
for ($low; $low =< $high; $low + $step) {}
you can write the code like this simple and specific :
`<?php`
$low = 0;
$high = 100;
$stepInc = 20;
$i ;
for ($i=$low; $i <= $high ; $i+=$stepInc) {
echo $i . "<br>";
}
?>
and the out will be:
0
20
40
60
80
100