在PHP中向后排序数组

<?php
    function apache($b) {
        return $b;
    }

    $a = array(1, 2, 3, 4, 5, 6);
    $num = "";

    foreach ($a as $b) {
        $num = apache($b) . $num ;
    }

    echo $num;
?>

When you write it like this the output is 654321, but if you write it like this:

$num = $num . apache($b);

the output would be 123456. I don't understand why the results are like that. Can someone explain this?

This isn't really hard to understand. This line:

$num = apache($b) . $num;

add the currently selected number and appends the current value of $num to it. The result will be written to $num. So this will happen:

$b.    $num = $num
1 .      "" = 1
2 .       1 = 21
3 .      21 = 321
4 .     321 = 4321
5 .    4321 = 54321
6 .   54321 = 654321

If you write

$num =  $num . apache($b);

instead, you're adding the currently selected number behind $num:

$num  .$b = $num
""    . 1 = 1
1     . 2 = 12
12    . 3 = 123
123   . 4 = 1234
1234  . 5 = 12345
12345 . 6 = 123456

one way you are appending to the string the other way you are prepending to the string

which gives the effect of reversing it.

first way kind of looks like this

[1]
2[1]
3[21]
4[321]
5[4321]
6[54321]

the other way looks like this

[1]
[1]2
[12]3
[123]4
[1234]5
[12345]6

where the value outside the [] is the value being returned by your function and the value inside the [] is $num