Recursive Functions and Reusable Code in PHP Practice Questions with Solutions

Introduction

Recursive Functions and Reusable Code in PHP to call itself to solve problems, while reusable code helps developers avoid writing the same code repeatedly. In this chapter, you will learn how to use recursion, create reusable PHP functions, and solve practical programming problems through simple examples.

Question 1: Print Numbers Using a Recursive Function

Problem Statement:
Write a PHP program to print numbers from 1 to 5 using a recursive function.

PHP Solution:

<?php

function printNumbers($num) {

    if ($num > 5) {
        return;
    }

    echo $num . "\n";

    printNumbers($num + 1);
}

printNumbers(1);

?>

Sample Output:

1
2
3
4
5

Explanation:

  • printNumbers() is a recursive function because it calls itself.
  • The function prints the current number.
  • It then calls itself with the next number.
  • When $num becomes greater than 5, the function stops.

Concepts Covered: Recursive functions, base condition, function calls.


Question 2: Calculate the Sum of Numbers Using Recursion

Problem Statement:
Write a PHP program to calculate the sum of numbers from 1 to 5 using recursion.

PHP Solution:

<?php

function calculateSum($num) {

    if ($num == 0) {
        return 0;
    }

    return $num + calculateSum($num - 1);
}

$result = calculateSum(5);

echo "Sum: " . $result;

?>

Sample Output:

Sum: 15

Explanation:

  • The function adds the current number to the result of the next recursive call.
  • Each call reduces the number by 1.
  • When the number reaches 0, the function returns 0.
  • The final result is 5 + 4 + 3 + 2 + 1 = 15.

Concepts Covered: Recursive calculations, return values, base condition.


Question 3: Calculate Factorial Using Recursion

Problem Statement:
Write a PHP program to calculate the factorial of a number using a recursive function.

PHP Solution:

<?php

function factorial($num) {

    if ($num <= 1) {
        return 1;
    }

    return $num * factorial($num - 1);
}

echo "Factorial: " . factorial(5);

?>

Sample Output:

Factorial: 120

Explanation:

  • Factorial means multiplying a number by all positive numbers below it.
  • The function multiplies the current number by the factorial of the previous number.
  • When the number becomes 1 or less, the function returns 1.
  • Therefore, 5! = 5 × 4 × 3 × 2 × 1 = 120.

Concepts Covered: Factorial, recursion, multiplication, base condition.


Question 4: Generate Fibonacci Series Using Recursion

Problem Statement:
Write a PHP program to generate the first 7 Fibonacci numbers using recursion.

PHP Solution:

<?php

function fibonacci($num) {

    if ($num <= 1) {
        return $num;
    }

    return fibonacci($num - 1) + fibonacci($num - 2);
}

for ($i = 0; $i < 7; $i++) {

    echo fibonacci($i) . " ";

}

?>

Sample Output:

0 1 1 2 3 5 8

Explanation:

  • The Fibonacci series starts with 0 and 1.
  • Every next number is the sum of the previous two numbers.
  • The recursive function calculates each Fibonacci number by calling itself twice.
  • The loop displays the first 7 numbers.

Concepts Covered: Fibonacci series, recursion, multiple recursive calls.


Question 5: Calculate Power Using Recursion

Problem Statement:
Write a PHP program to calculate the power of a number using recursion. For example, calculate 2 raised to 4.

PHP Solution:

<?php

function calculatePower($base, $power) {

    if ($power == 0) {
        return 1;
    }

    return $base * calculatePower($base, $power - 1);
}

echo "Result: " . calculatePower(2, 4);

?>

Sample Output:

Result: 16

Explanation:

  • The function receives a base number and a power.
  • It multiplies the base by the result of the next recursive call.
  • When the power becomes 0, it returns 1.
  • Therefore, 2 × 2 × 2 × 2 = 16.

Concepts Covered: Recursive multiplication, function parameters, base condition.


Question 6: Create a Reusable Function to Calculate Employee Salary

Problem Statement:
Create a reusable PHP function that calculates an employee’s final salary by adding basic salary and allowance.

PHP Solution:

<?php

function calculateSalary($basicSalary, $allowance) {

    return $basicSalary + $allowance;
}

echo "Employee 1 Salary: " . calculateSalary(25000, 5000) . "\n";

echo "Employee 2 Salary: " . calculateSalary(30000, 7000) . "\n";

echo "Employee 3 Salary: " . calculateSalary(35000, 8000);

?>

Sample Output:

Employee 1 Salary: 30000
Employee 2 Salary: 37000
Employee 3 Salary: 43000

Explanation:

  • calculateSalary() is a reusable function.
  • It accepts basic salary and allowance as arguments.
  • It returns the final salary.
  • The same function calculates salaries for multiple employees without repeating the calculation code.

Concepts Covered: Reusable functions, parameters, arguments, return values.


Question 7: Create a Reusable Function to Calculate Student Results

Problem Statement:
Create a reusable function that accepts marks in three subjects and calculates the total and average marks.

PHP Solution:

<?php

function calculateResult($english, $maths, $computer) {

    $total = $english + $maths + $computer;

    $average = $total / 3;

    return [
        "total" => $total,
        "average" => $average
    ];
}

$result = calculateResult(80, 90, 85);

echo "Total Marks: " . $result["total"] . "\n";

echo "Average Marks: " . $result["average"];

?>

Sample Output:

Total Marks: 255
Average Marks: 85

Explanation:

  • The function accepts marks for three subjects.
  • It calculates the total and average.
  • Both results are returned in an associative array.
  • The returned values can be accessed using their keys.

Concepts Covered: Reusable functions, associative arrays, returning multiple results.


Question 8: Create a Reusable Function to Calculate Product Discount

Problem Statement:
Create a reusable function that calculates the final product price after applying a discount percentage.

PHP Solution:

<?php

function calculateDiscount($price, $discount) {

    $discountAmount = ($price * $discount) / 100;

    $finalPrice = $price - $discountAmount;

    return $finalPrice;
}

echo "Product 1 Price: " . calculateDiscount(2000, 10) . "\n";

echo "Product 2 Price: " . calculateDiscount(5000, 20) . "\n";

echo "Product 3 Price: " . calculateDiscount(3000, 15);

?>

Sample Output:

Product 1 Price: 1800
Product 2 Price: 4000
Product 3 Price: 2550

Explanation:

  • The function accepts the original price and discount percentage.
  • It calculates the discount amount.
  • It subtracts the discount from the original price.
  • The same function can calculate discounted prices for different products.

Concepts Covered: Reusable functions, percentage calculations, return values.


Question 9: Find the Sum of Digits Using Recursion

Problem Statement:
Write a PHP program to calculate the sum of all digits of a number using recursion.

PHP Solution:

<?php

function sumOfDigits($num) {

    if ($num == 0) {
        return 0;
    }

    return ($num % 10) + sumOfDigits((int) ($num / 10));
}

$number = 12345;

echo "Sum of Digits: " . sumOfDigits($number);

?>

Sample Output:

Sum of Digits: 15

Explanation:

  • % 10 extracts the last digit of the number.
  • Dividing the number by 10 removes its last digit.
  • The function adds the extracted digit to the result of the next recursive call.
  • When the number becomes 0, the function returns 0.
  • Therefore, 1 + 2 + 3 + 4 + 5 = 15.

Concepts Covered: Recursive functions, modulus operator, integer conversion.


Question 10: Create a Reusable Employee Salary Report

Problem Statement:
Create a reusable PHP function that calculates the final salary of multiple employees using their basic salary and allowance. Display the employee name and final salary.

PHP Solution:

<?php

function calculateSalary($basicSalary, $allowance) {

    return $basicSalary + $allowance;
}

function displayEmployee($name, $basicSalary, $allowance) {

    $finalSalary = calculateSalary($basicSalary, $allowance);

    echo "Employee Name: " . $name . "\n";

    echo "Basic Salary: " . $basicSalary . "\n";

    echo "Allowance: " . $allowance . "\n";

    echo "Final Salary: " . $finalSalary . "\n\n";
}

displayEmployee("Rahul", 25000, 5000);

displayEmployee("Priya", 30000, 7000);

displayEmployee("Amit", 35000, 8000);

?>

Sample Output:

Employee Name: Rahul
Basic Salary: 25000
Allowance: 5000
Final Salary: 30000

Employee Name: Priya
Basic Salary: 30000
Allowance: 7000
Final Salary: 37000

Employee Name: Amit
Basic Salary: 35000
Allowance: 8000
Final Salary: 43000

Explanation:

  • calculateSalary() calculates the final salary.
  • displayEmployee() displays employee information.
  • The display function reuses the salary calculation function.
  • Both functions work together to create a reusable employee salary report.

Concepts Covered: Reusable code, function reuse, nested function calls, parameters and return values.


Key Takeaways

  • A recursive function calls itself to solve a problem.
  • Every recursive function needs a stopping condition, also called a base condition.
  • Recursion is useful for factorials, Fibonacci series, digit calculations, and similar problems.
  • Reusable functions help avoid writing the same code repeatedly.
  • Functions can accept multiple parameters and return calculated results.
  • One function can call another function to complete a task.
  • Reusable code makes PHP programs easier to maintain and update.

FAQs: Recursive Functions and Reusable Code in PHP

1. What is a recursive function in PHP?

A recursive function is a function that calls itself to solve a problem repeatedly until a stopping condition is reached.

2. What is a base condition in recursion?

A base condition is the condition that stops a recursive function from calling itself again.

3. What happens if a recursive functions has no base condition?

The function may continue calling itself until PHP runs into resource or execution limits, resulting in an error or failed execution.

4. What is reusable code in PHP?

Reusable code is code written once and used multiple times in a program. PHP functions are a common way to create reusable code.

5. What is the difference between recursion and a loop?

A loop repeats a block of code using statements such as for or while. Recursion repeats a task through function calls.

6. Can a recursive function return a value?

Yes. A recursive function can return a value from its base condition and combine results from earlier function calls.

7. Can one PHP function call another function?

Yes. One function can call another function to reuse its functionality and perform related operations.

8. Where are recursive functions used in real projects?

Recursive functions are commonly used for folder structures, nested categories, tree data, menu systems, and hierarchical data processing.

9. Is recursion always better than loops?

No. Recursion can make some problems easier to understand, but loops are often more memory-efficient for simple repetitive tasks.

10. Why should developers write reusable functions?

Reusable functions reduce duplicate code, improve readability, simplify testing, and make programs easier to maintain.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top