How can I find and print all of the numbers between two numbers in PHP?

≡放荡痞女 提交于 2019-12-12 19:08:38

问题


Right now I'm asking the user for two numbers. I'm trying to print the numbers in between $one and $two assuming $one is smaller than $two.


回答1:


Just a simple for loop should do the trick:

for($i=$a; $i<=$b; $i++) {
  echo $i;
}



回答2:


range gives an array containing all the numbers.

You can iterate over that:

foreach (range($one, $two) as $number)
    echo "$number <br>\n";

Or simply use a loop:

for ($number = $one; $number <= $two; $number++)
    echo "$number <br>\n";



回答3:


<?php
foreach (range($one, $two) as $number) {
    echo $number." \n";
}
?>

range($one, $two) makes an array of numbers from $one to $two.

<?php
$numbers = range($one, $two);
foreach ($numbers as $number) {
    echo $number." \n";
}
?>

In this example, the array of numbers are first stored in $numbers before they are printed.

If $one is 5 and $two is 10 these examples will output:

5 
6 
7 
8 
9 
10 



回答4:


This sounds like homework...

for ($i=$one+1; $i<$two; $i++)
{
  echo $i . "\n";
}

This really gets you only the numbers between, not the endpoints.




回答5:


for($i=$one + 1; $i<$two; $i++) {
    echo $i;
}


来源:https://stackoverflow.com/questions/5033170/how-can-i-find-and-print-all-of-the-numbers-between-two-numbers-in-php

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