Jump to content

Reverse an array


Saggi
 Share

Recommended Posts

Hi all, Need help in solving this task using PHP built in function : array_reverse() and without it. Appreciate it in explaining the code as I'm completely a newbie. 

function reverseArray($Arr) {
		
	 }
	 $fruits = ["Mango","Strawberry","Bananas","Pineapple"];
	 $result = reverseArray($fruits);

Many thanks, 

 

Link to comment
Share on other sites

4 hours ago, NotSunfighter said:

Or use array_reverse'

 


<?php
$input  = array("Name", 1, 2, 3, array("red", "green"), 4, "life");
$reversed = array_reverse($input);
	print_r($input);
echo '---<br>';
print_r($reversed);
echo '---<br>';
?>
	

 

$fruits = ["Mango","Strawberry","Bananas","Pineapple"];
   
function reverseArray($Arr) {
	return array_reverse($Arr);
   }
   $result = reverseArray($fruits);
   print_r($result);

Output: Array ( [0] => Pineapple [1] => Bananas [2] => Strawberry [3] => Mango ) 

 

Link to comment
Share on other sites

15 minutes ago, Barand said:

So you can do it the easy way. What about the solutions not using array_reverse?

I tried without using array_reverse and 

Here is my other solution: 
 

$fruits = ["Mango","Strawberry","Bananas","Pineapple"];
function reverseArray($Arr) {
        $fruitsReverse = [];
		for($i=count($Arr)-1; $i>=0; $i--) {
           array_push($fruitsReverse,$Arr[$i]);
          }
          return $fruitsReverse;
	     }
	   $result = reverseArray($fruits);
	   print_r($result);

 

Edited by Saggi
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.