skip to Main Content

Right now, I’m trying to print the numbers in between two ranges assume 1 to 48 and 114 to 118 using a for loop.
I tried the following to do this :

for ($y = 1; $y < 48; $y++) { }

The loop printed numbers in the range 1 to 48 correctly.
But I haven’t a clear idea to apply the second range 114 to 118 to print numbers as 115, 116 and 117 in another range.

I want to print the numbers as 1,2,3,……………..45,46,47,115,116,117
Anyone can help on this for me ?

3

Answers


  1. One of the ways is: use a conditional statment to print what you want to include

    <?php
    for ($y=1; $y < 118; $y++) {
      if (($y>=1 && $y<=48) || ($y>=115 && $y <=117)) {
       echo $y . " " ;
      } else {  
       // do nothing
      }
    }  
      ?>
    

    See demo

    Login or Signup to reply.
  2. <?php 
      for ($y = 1; $y < 118; $y++) {
        if (($y >= 1 && $y < 48) || ($y >= 115 && $y < 118)) {
            echo $y . ",";
        }
      } 
    ?>
    
    Login or Signup to reply.
  3. For a solution that is both efficient and easy to read you could use something like this:

    foreach ([...range(1, 48), ...range(114, 118)] as $number) {
        echo "$number ";
    }
    

    This makes use of range(), the the ... operator, short array notation, and foreach.

    See: https://3v4l.org/l8ril

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search