Home > Article > Backend Development > How to reverse array in php
The method to achieve array reversal in php is: 1. Use the syntax "function reverse($arr){...}" to achieve array reversal, but this function can only handle one-dimensional arrays; 2. Use the syntax "function reverse_arr($arr){...}" to achieve array reversal. This function can handle multi-dimensional arrays.
The operating environment of this tutorial: Windows 10 system, php8.1.3 version, dell g3 computer
php implements array reversal:
There is a function in php that can reverse an array. It is often used in work and is very convenient. Let’s implement this function by ourselves today.
$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; } 效果 Array ( [0] => 12 [1] => 16 [2] => 8 [4] => 6 [5] => 5 [6] => 2 )
However, this function can only handle one-dimensional arrays. While implementing one that can handle multiple dimensions.
$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))); 输出结果
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 )
The above are all numeric index arrays and cannot handle associative arrays. Next comes the one that 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)); 结果 Array ( [e] => ee [d] => dd [c] => cc [b] => bb [a] => aa )
The above is the detailed content of How to reverse array in php. For more information, please follow other related articles on the PHP Chinese website!