PHP Exercise : Recursion Function in PHP

Write a program to print numbers from 10 to 1 using the recursion function.


Recursion function is a function which is call itself. In the given example, we have called the recursion function to print the prime numbers from 10 to 1. A recursion function continues until some condition is met to prevent it. That's why, we use the if statement to break the infinite recursion.

function countdown($num_arg) 
	if($num_arg > 0)
		print("Number is $num_arg<br>");
		countdown($num_arg - 1);

Output of the above code

Number is 10
Number is 9
Number is 8
Number is 7
Number is 6
Number is 5
Number is 4
Number is 3
Number is 2
Number is 1

In the recursion function, it is important to maintain the base value. If the base value is never invoked, in the above case, the infinite recursion function happened or it goes down to negative numbers. In the above example, countdown() function calls itself.

Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database

Read more articles

General Knowledge

Learn Popular Language