Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an array in php WITHOUT using the array reverse method

I want to know how to reverse an array without using the array_reverse method. I have an array called reverse array which is the one i want to reverse. My code is below. could someone point out what i am doing wrong as I cannot find any example of reversing an array this way anywhere else. my code is below.

<?php

//Task 21 reverse array

$reverseArray = array(1, 2, 3, 4);
$tmpArray = array();
$arraySize = sizeof($reverseArray);

for($i<arraySize; $i=0; $i--){
    echo $reverseArray($i);
}

?>
like image 572
Ciaran Avatar asked Apr 30 '15 09:04

Ciaran


2 Answers

<?php
  $array = array(1, 2, 3, 4);
  $size = sizeof($array);

  for($i=$size-1; $i>=0; $i--){
      echo $array[$i];
  }
?>
like image 92
Robert Avatar answered Sep 23 '22 21:09

Robert


Below is the code to reverse an array, The goal here is to provide with an optimal solution. Compared to the approved solution above, my solution only iterates for half a length times. though it is O(n) times. It can make a solution little faster when dealing with huge arrays.

<?php
  $ar = [34, 54, 92, 453];
  $len=count($ar);
  for($i=0;$i<$len/2;$i++){

    $temp = $ar[$i];
    $ar[$i] = $ar[$len-$i-1];
    $ar[$len-$i-1] = $temp;
  }

  print_r($ar)

?>
like image 29
Sai Amar Nath Chintha Avatar answered Sep 23 '22 21:09

Sai Amar Nath Chintha