While Loop Store In Array

Discussion in 'PHP' started by ironmankho, Feb 12, 2013.

  1. #1
    Hi folks
    i want to store while loop in array how it is possible?

    e.g
    <?php
    $i=1;
    while($i<=5)
      {
      echo $i . "<br>";
      $i++;
      }
    ?>
    
    Code (markup):
    my requirements
    $store_array=[1,2,3,4,5];
     
    ironmankho, Feb 12, 2013 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    While you COULD do this:

    <?php
    $store_array=array(); // make empty array
    $i=1;
    do {
    	echo $i,'<br />';
    	$store_array[]=$i; // an empty index [] appends to end of array
    } while ($i++ < 5);
    ?>
    Code (markup):
    If ALL you want to do is plug in a range of numbers, PHP already has a function for that.

    $store_array=range(1,5);

    Will create an array containing what you described.
    http://php.net/manual/en/function.range.php
     
    deathshadow, Feb 12, 2013 IP
  3. 007speed

    007speed Member

    Messages:
    38
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    38
    #3
    Here you go
    You can do it using the for loop

    <?php
    $numbers = array();
    for( $i = 1 ; $i < 6; $i++ ) {
        $numbers[] = $i;
    }
    ?>
    Code (markup):
    or the while loop
    $numbers = array();
    $i = 1;
     
    while( $i < 6 ){
        $numbers[] = $i;
        $i++;
    }
    Code (markup):
     
    007speed, Feb 18, 2013 IP