How to Use Recursion in PHP?

Recursion is a very easy concept in PHP. When a function calls itself again and again until exit condition met, that is recursion. That is it. It is very obvious that exit condition, or base case written in many books, is just placed there to end the otherwise endless loop of function calling itself. May be just for fun try writing a function which just calls itself. It will never end and until your compiler will run short of memory stacks. So we place exit condition.

Lets code a very simple case. Just to get understanding of a very interesting concept.

$numbers = [ 12, 10, 2, 11, 4, 8, 9, 6, 7, 1, 3, 5 ];

$total   = 0;
function sum_function( $size, $numbers, $total ) {
	$total += $numbers[ $size ];

	if ( $size < 0 ) {
		return $total;
	$size --;

	return sum_function( $size, $numbers, $total );

In this code we are summing up all elements of array by calling function in itself until we reach at the end of the array. Fairly simple! Answer will be 78 which is sum of first 12 positive integers. We can also solve this problem by just looping through the array.

Let’s discuss that with another complex example where we do not have luxury of looping through our dataset. We want to show every file in every directory of some directory in PHP. Now you may say we use loops but how many loops we need? Number of directories and files can change randomly. So we use recursion where put every directory through our calling function again and again until it meets exit condition, which is the directory having no directory left to scan. Now we are clear what we want to do so lets write some code for that.

function getDirectoryContent( $dir, &$results = array() ) {
	$files = scandir( $dir );

	foreach ( $files as $key => $value ) {
		$path = realpath( $dir . DIRECTORY_SEPARATOR . $value );
		if ( ! is_dir( $path ) ) {
			$results[] = $path;
		} else if ( $value != "." && $value != ".." ) {
			$results[] = $path;
			getDirectoryContent( $path, $results );

	return $results;

Now here is the output of my JS folder in some random projects.

It is showing every file in every directory in given folder.