Write a PHP Program to print 5 to 15 using Conditional statements

Description: Write a PHP program to print the numbers from 5 to 15 using conditional statements, without using any loop.

Rules and hints:

  • You can use a function with arguments.
  • You can not use a loop (for, while, foreach).
  • You can use if conditions.

PHP program to print 5 to 15 without a loop

<?php
function printNumbers($current, $end) {
    if ($current > $end) {
        return;                       // stop
    }

    echo $current . "<br>";
    printNumbers($current + 1, $end); // call the function again
}

printNumbers(5, 15);
?>

Output:

Tutorials Class - Output Window

5
6
7
8
9
10
11
12
13
14
15

How it works

  • The function prints the current number, and then calls itself with the next number.
  • When the current number becomes bigger than the end number, the if condition stops the function. This is called recursion.

Read about PHP functions and see another example of recursion in factorial using recursion.


Learn more about the similar topics:
Tutorials
PHP Decision Making
PHP match Expression
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Write a PHP Program to print 5 to 15 using Conditional statements
Interview Questions & Answers
No Content Found.