Array Looping in PHP

I remember back when I as learning PHP I had to write a directory “spider” function to list the contents of a directory. (Including sub-directories).

The approach I took involved reading the initial contents of the base directory into an array. The plan was then to loop through the array adding any sub-directories, (and their files), recursively.

In my naivety, I assumed that I could do something similar to:

foreach($results as $result){
	if(is_dir($result)){
		//Add directory's contents...
	}
}

But, I quickly learned that the foreach construct works on a copy of the array, so adding to it in a recursive fashion is not possible. Bum.
There’s a fairly simple solution to the problem though:

for($i=0; ; $i++){ //Infinite loop
	if($i < count($results)){
		$result = $results[$i];
		if(is_dir($result)){
			//Add directory's contents...
		}
	}
	else break; //Nothing left to process, so break out of the loop
}
Share Button