count between 2 inputted numbers (range) & display each

不想你离开。 提交于 2019-12-25 18:34:47

问题


My attempt is below; to first start with a while loop to create the array, then iterate through each with a foreach in attempt to count each item in array.

$begin = $_POST['startpoint'];
$end = $_POST['endpoint'];

$current_start = $begin;

$num1 = 3;
$num2 = 355;

while ($i = $begin; $i <= $end; ++$i) {
    $array[] = $i;
  foreach ($array as &$counted) {
    echo '<span>Star SC ' + $counted + ' mag ' + $num1 + $num2;
  }    
}

the desired output would be something like this; if user inserted say 10002 and 80000:

Output 1.) Star C 69998 mag...

and

Output 2.)

10002
10003
10004
10005

(all the way to 80000)


html:

<form action="script.php" method="post">

  <input type="number" name="startpoint" min="100000" max="999998">
  <input type="number" name="endpoint" min="100001" max="999999">

  <input type="submit" name="submit" value="Go!" />

</form>

more details: I would like to count, so do the math between each user inputed number (ie. 69998); and display each numbers between, so with the above user example; it would be 10002, 10003, 10004 - all the way to 80000 .


回答1:


If all you want to do is output each line you would do it like this:

$begin = 10002;
$end = 80000;

$current_start = $begin;

$num1 = 3;
$num2 = 355;

for($i = $begin; $i <= $end; $i++) {
    echo '<span>Star SC ' . $i . ' mag ' . $num1 .', '. $num2;
}

. is concatenation in PHP, not + and you need a for() loop, not a while(). In addition, you do not need to utilize yet another array for your output.

Output is

<span>Star SC 10002 mag 3, 355
...
<span>Star SC 80000 mag 3, 355



回答2:


I really do not understand your intention, but for a memory friendly solution, you should use generator function.

function numbers_between($n1, $n2) {
  for($n1; $n1 <= $n2; $n1++) {
    yield $n1;
  } 
}
$generator = numbers_between(1,5);

foreach($generator as $genval){
  echo $genval."\n";
}

if you want the total number count, just do basic math, like

($num2 - $num1)+1

link to working code snippet




回答3:


The correct way is

foreach (range($begin, $end) as $number) {
    echo $number;
}


来源:https://stackoverflow.com/questions/49949371/count-between-2-inputted-numbers-range-display-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!