Changing arrays at runtime

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aktar
    New Member
    • Jul 2006
    • 105

    #1

    Changing arrays at runtime

    Here is the code


    [PHP]$alphabet = array("a","b"," c");
    $number_of_lett ers = 3; //initial amount of characters

    foreach($alphab ets as $letter)
    {
    print $letter;

    if ($number_of_let ters != 26)
    {
    //add another character to the $alphabet array
    //AND increase the $number_of_lett ers by 1
    }
    }[/PHP]

    Now here is the question :

    The above code will only process the initial array values even thoug the array is being added to, ie it will print only a,b and c

    Logically, it should carry on printing as the $aphabet array is being continiously chaged.

    Any thoughts appreciated
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, Aktar.

    In this case, you'll want to use a for loop, as the condition is evaluated at every iteration:

    [code=php]
    for( $__i = 0; $__i < $number_of_lett ers; ++$__i )
    {
    .
    .
    .
    }
    [/code]

    When you add a letter to the array, be sure to increment $number_of_lett ers. Once you stop adding letters, your script will stop incrementing $number_of_lett ers, and then your loop will (eventually) terminate.

    Comment

    Working...