What are Iteration Functions ?

Discussion in 'PHP' started by clobberx, Jun 20, 2008.

  1. #1
    What are Iteration Functions ?
     
    clobberx, Jun 20, 2008 IP
  2. Typo3 Steve

    Typo3 Steve Peon

    Messages:
    64
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    If you need to iterate in an array, you can simply use the for loops... and to see the amount of elements you have in an array, you can use the count() function.

    Here is an example:

    
    
    //we add data inside our array & create our array keys:
    $arr_data = array('index_01' => 'ananas', 'index_02' => 'bananas');
    $arr_keys = array_keys($arr_data);
    
    //we then loop in ou array:
    for($i = 0; $i < count($arr_data); $i++)
    {
             echo $arr_data[$arr_key[$i]].'<br />';
    }
    
    PHP:
     
    Typo3 Steve, Jun 20, 2008 IP
  3. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #3
    Bah, make sure you always set the count variable before you put it in the loop, or it will be repeated each time.

    Real waste of memory.

    Dan
     
    Danltn, Jun 20, 2008 IP
  4. Typo3 Steve

    Typo3 Steve Peon

    Messages:
    64
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The count function just returns the next index of the array... it doesnt really calculate anything, just returns an integer. That beeing said, if you add the count values inside a variable, you will copy an integer inside another variable.

    In other words, if you want to use less memory, use count directly.

    Steve
     
    Typo3 Steve, Jun 20, 2008 IP
  5. andrews

    andrews Peon

    Messages:
    34
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    This is not true, please check php.net/count.

    It's more efficient to save the count() value in a new variable because the count() function must go through all the array elements to return the last index.
     
    andrews, Jun 20, 2008 IP