Friday, 25 May 2007

Methods To Recurse 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,

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


1. Using a simple for loop


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

2. Using foreach

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


3. Using a while loop


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


4. Using the array_walk function


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

array_walk($arr,'print_item');


5. Using an user function

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

No comments: