Recursion Function in PHP

by  
Share:
php

Recursion in programming means calling to itself. In this snippet you will see how to make recursive function that calls to itself until some conditions are met which breaks the loop. Recursion in PHP is same as recursion in any other languages its just a concept so don’t be nervous about anything.

Simple recursive function to get a factorial of a number

function factorial($var) {
  if ($var <= 1) {
	// if it is not zero
     return 1;
  }
  else {
     // will add the value and call itself
     return $var * factorial($var-1); 
  }

}
echo factorial(5); // results 120
echo factorial(6); // results 720
echo factorial(1); // results 1

For advance recursive call with PHP and MySQl check this tutorial Create Category tree with PHP and mysql

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.