Recursive Functions in PHP (Simple Examples)

A recursive function is a regular function which calls itself..


// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {

	if ($n == 1) return 1;
	return $n * factorial($n-1);

}

echo factorial(5); // Outputs 120

// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);

function sum_array($array) {

	$total = 0;
	foreach ($array as $element) {
		if(is_array($element)) {
			$total += sum_array($element);
		} else {
			$total += $element;
		}
	}
	return $total;

}
echo sum_array($example); // Outputs 67
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>