Get the App
SLTechnology News&Howtos  ›  Development  › 

How to reverse the php array

Shulou Source: shulou.com Published: 2022-06-02 07:14:03 10月01日 Update

This article mainly explains "how to reverse php array", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to reverse php array"!

Php array inversion implementation method: 1, use "function reverse($arr){...} "method implements array inversion;2. Use"function reverse_arr($arr){...} "The array can be inverted using the method.

Operating environment: Windows 7 system, PHP 7.4 version, Dell G3 computer.

Php implements array inversion

There is a function in php that can invert arrays, and it is often used in work. Today, I am going to perform this function myself.

$arr = [2,5,6,1,8,16,12];function reverse($arr){ $left = 0; $right = count($arr) -1; $temp = []; while ($left 12 [1] => 16 [2] => 8 [4] => 6 [5] => 5 [6] => 2)

However, this function can only handle one-dimensional arrays. In implementing a multi-dimensional.

$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 result Array( [0] => 0 [1] => 5 [2] => Array ( [0] => Array ( [0] => 7 [1] => 8 [2] => 10 ) [1] => 1 [2] => 2 [3] => 5 ) [3] => 1 [4] => Array ( [0] => 9 [1] => 3 [2] => 6 ) [5] => 2)

Above are numerical index arrays, can not handle associative arrays, and then to a can handle associative arrays

$arr = ['a'=>'aa','b'=>'bb','c'=>'cc','d'=>'dd','e'=>'ee'];function reverse($arr){ $temp = []; end($arr); while (($value = current($arr)) != null){ $temp[key($arr)] = $value; prev($arr); } return $temp;}print_r(reverse($arr)); result Array( [e] => ee [d] => dd [c] => cc [b] => bb [a]=> aa) At this point, I believe that everyone has a deeper understanding of "how to invert php arrays", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Arrays methods processing content functions results associations learning practicality deeper interest function practicality practicality simplicity of operation numbers more friends environment computer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS OPPO Reno Apple Shulou Technology MySQL