Methods to iterate through an array

Discussion in 'PHP' started by pradeep, May 9, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    I was wondering in how many ways can we iterate through an array in PHP. So, I figured out a few, here's it...

    Our Array, which we will be iterating on,
    PHP:
    $arr = array('PHP','Perl''JavaScript','AJAX''Python','ASP''C#');
    1. Using a simple for loop
    PHP:
    // using for loop
     
    for($i=0;$i<count($arr);$i++)
     {
         print(
    "$arr[$i]\n");
     }
     
    2. Using foreach
    PHP:
    // using foreach
     
    foreach($arr as $val)
     {
         print(
    "$val\n");
     }
    3. Using a while loop
    PHP:
    // using while loop
     
    $i=0;
     while(
    $val=$arr[$i++])
     {
         print(
    "$val\n");
     }
    4. Using the array_walk function
    PHP:
    // using array_walk function
     
    function print_item($item,$key)
     {
         print(
    "$item\n");
     }
     
     
    array_walk($arr,'print_item');
     
    5. Using an user function
    PHP:
    // using a function, and recursively calling it
     
    function print_recurse(&$a)
     {
         
    printf("%s\n",array_pop($a));
         
    print_recurse($a);
     }
     
     
    print_recurse($arr)
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Sorry for the bug which I overlooked, the function will run into infinite recursion, so the correct one should look like this.

    PHP:
     // using a function, and recursively calling it
    function print_recurse(&$a)
    {
        
    printf("%s\n",array_pop($a));
        
    // check whether array has any elements, or else it'll become an infinite recursion
        
    if(count($a)>0)
            
    print_recurse($a);
    }

    print_recurse($arr);
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice