Why PHP prints this function in reverse after swapping two lines without changing the condition

Viewed 35

I have a displayNumber code which prints the input number if its greater than 1 and then calls the displayNumber function again with the number - 1.

function displayNumber($number) {
    if ($number >= 1) {
        echo $number;
        displayNumber($number-1);
    }

    return;
}

displayNumber(10);

The output would be: 10987654321

But after swapping the echo and displayNumber lines:

function displayNumber($number) {
    if ($number >= 1) {
        displayNumber($number-1);
        echo $number;
    }

    return;
}

displayNumber(10);

The output is now: 12345678910

I can't understand this behavior of PHP.

1 Answers

I modified your code to make it more understandable:

function displayNumber($number) {
    if ($number >= 1) {
        echo $number ."<br>";
        displayNumber($number-1);
        echo $number . "---";
    }
}

displayNumber(10);

Output:

10
9
8
7
6
5
4
3
2
1
1---2---3---4---5---6---7---8---9---10---

In the first case, values are being printed, then decremented by 1. In the second case, values are decremented by 1 and then printed.

Also, the first echo, runs every time, but this does not happen for the second echo as the function is called just before it.

Related