php - 找出范围之间的适当减量值

I'm not quite sure how to phrase the question succinctly... also, I'm sure this boils down to basic math failure. Anyways, my goal is to count from 1 to 20, but then assign a decremented value to the count, starting from 80 and ending in 2.

So basically,

$array = (
  1 => 80,
  ..
  20 => 2
);

Here is the code I have come up with, and it seems really close but it's off, and I can't figure out why :(

$array = array();
for( $x = 1; $x <= 20; $x++ ) {
  $y = ( 80 - 2 ) / 20;
  $p = ( 80 - ( $x * $y ) ) + ( $y / $x );
  $array[$x] = $p;
}
echo "<pre>";
print_r($array);
echo "</pre>";

this gives me:

Array
(
    [1] => 80
    [2] => 74.15
    [3] => 69.6
    [4] => 65.375
    [5] => 61.28
    [6] => 57.25
    [7] => 53.2571428571
    [8] => 49.2875
    [9] => 45.3333333333
    [10] => 41.39
    [11] => 37.4545454545
    [12] => 33.525
    [13] => 29.6
    [14] => 25.6785714286
    [15] => 21.76
    [16] => 17.84375
    [17] => 13.9294117647
    [18] => 10.0166666667
    [19] => 6.10526315789
    [20] => 2.195
)

Could someone point out where I'm going wrong or nudge me in the right direction?

What you want is:

$array = array();
for ($x=1;$x<=20;$x++) {
  $y = (80-2)/(20-1);
  $p = 80-($x-1)*$y;
  $array[$x] = $p;
}

Explanation: you start with 80 and end with 2. Your indexes go from 1 to 20. That means, you have 20 elements, but the first and the last are fixed. So, you have 20-1 = 19 "jumps" (or subtractions) until you reach the 2 from the 80. each jump has the same size. Since the total difference is 80-2, then each subtraction should have (80-2)/(20-1) = 78/19 as a size.

That's why you should write

$p = 80-($x-1)*$y;

Note that the ($x-1) is due to the fact that the subtraction only starts on the second element (you want to start with 80).

Your problem is primarily on this line:

$y = ( 80 - 2 ) / 20;

While there are 20 values, there are only 19 instances where you need to subtract. Here's my chicken scratch, same as the other answer, mostly:

$array = array();
for ( $x=1; $x <= 20; $x++ ) 
{
  $y = (80 - 2) / 19;
  $p = 80 - ($y * ($x - 1));
  $array[$x] = $p;
}

print_r($array);