PHP implements array inversion

Source: Internet
Author: User

PHP has a function to reverse the array, the work is also often used, very convenient. Today to implement such a function yourself.

$arr = [2,5,6,1,8,16,12];function reverse ($arr) {    $left = 0;    $right = count ($arr)-1;    $temp = [];    while ($left <= $right) {        $temp [$left] = $arr [$right];        $temp [$right]  = $arr [$left];        $left + +;        $right--;    }    Ksort ($temp);    return $temp;} Effect Array (    [0] = [    1] = [    2] = 8    [4] = 6    [5] = 5    [6] = 2)

However, this function can only handle one-dimensional arrays. In the implementation one can handle multidimensional.

 $arr = [2,[6,3,9],1,[5,2,1,[10,8,7]],5,0];function Reverse_arr ($arr) {$index = 0    ;    $reverse _array = [];            foreach ($arr as $sub _arr) {if (Is_array ($sub _arr)) {$sub _arr = reverse ($sub _arr);            $arr _ = Reverse_arr ($sub _arr);        $reverse _array[$index] = $arr _;        }else{$reverse _array[$index] = $sub _arr;    } $index + +; } return $reverse _array;} Print_r (Reverse (Reverse_arr ($arr))); 

Output
Array(    [0] = 0    [1] = 5    [2] = = Array        ( [0] = = Array ( [0] = > 7 [1] = 8 [2] = [  1] = 1 [2] = 2 [3] = 5 ) [3] = = 1 [4] = = Array ( [0] = 9 [1] = 3 [2] = 6 ) [5] = 2) /c30> 

PHP implements array inversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.