PHP 反转数组

要求:不用内置array_reverse()函数

答案

  1. function reverseArray($arr)
  2. {
  3. $n = count($arr);
  4. $left = 0;
  5. $right = $n - 1;
  6. while ($left < $right) {
  7. $temp = $arr[$left];
  8. $arr[$left++] = $arr[$right];
  9. $arr[$right--] = $temp;
  10. }
  11. return $arr;
  12. }

测试代码:

  1. $arr = [11, 22, 33, 44, 55, 66, 77];
  2. // 输出:[77,66,55,44,33,22,11]
  3. echo json_encode(reverseArray($arr));