Zack Shapiro
Zack Shapiro

Reputation: 6998

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

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.

Upvotes: 7

Views: 18706

Answers (5)

user479911
user479911

Reputation:

<?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 

Upvotes: 5

Sean Walsh
Sean Walsh

Reputation: 8344

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

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270609

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.

Upvotes: 0

coreyward
coreyward

Reputation: 80041

Just a simple for loop should do the trick:

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

Upvotes: 2

aaz
aaz

Reputation: 5196

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";

Upvotes: 20

Related Questions