简体   繁体   中英

backward sorting array in 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM