Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Methods to iterate through an array (http://www.go4expert.com/articles/methods-iterate-array-t4252/)

pradeep 9May2007 20:00

Methods to iterate through an array
 
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 Code:

$arr = array('PHP','Perl''JavaScript','AJAX''Python','ASP''C#'); 

1. Using a simple for loop
PHP Code:

// using for loop
 
for($i=0;$i<count($arr);$i++)
 {
     print(
"$arr[$i]\n");
 } 

2. Using foreach
PHP Code:

// using foreach
 
foreach($arr as $val)
 {
     print(
"$val\n");
 } 

3. Using a while loop
Code: PHP

// using while loop
 $i=0;
 while($val=$arr[$i++])
 {
     print("$val\n");
 }

4. Using the array_walk function
PHP Code:

// using array_walk function
 
function print_item($item,$key)
 {
     print(
"$item\n");
 }
 
 
array_walk($arr,'print_item'); 

5. Using an user function
PHP Code:

// using a function, and recursively calling it
 
function print_recurse(&$a)
 {
     
printf("%s\n",array_pop($a));
     
print_recurse($a);
 }
 
 
print_recurse($arr


pradeep 10May2007 00:08

Re: Methods to iterate through an array
 
Sorry for the bug which I overlooked, the function will run into infinite recursion, so the correct one should look like this.

PHP Code:

 // 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); 



All times are GMT +5.5. The time now is 01:46.