Posted on by Kalkicode
Code Recursion

Reverse array using recursion in php

Php program for Reverse array using recursion. Here problem description and explanation.

<?php
// Php program for
// Reverse array using recursion
class Transformation
{
	// print array elements
	public	function display($data, $size)
	{
		// Loop which is iterating array elements
		for ($i = 0; $i < $size; ++$i)
		{
			echo "  ",$data[$i];
		}
		echo "\n";
	}
	// This is reversing the array elements of given array
	public	function reverseArray(&$data, $front, $tail)
	{
		if ($front < $tail)
		{
			// Swap the array elements
			$auxiliary = $data[$front];
			$data[$front] = $data[$tail];
			$data[$tail] = $auxiliary;
			// Recursive execute
			$this->reverseArray($data, 
                                $front + 1, 
                                $tail - 1);
		}
	}
	public static
	function main($args)
	{
		$task = new Transformation();
		// Define array of integer elements
		$data = array(1, 2, 7, 3, 4, 5, 8, 9);
		// Get the size of array
		$size = count($data);
		echo " Before Reverse \n";
		$task->display($data, $size);
		$task->reverseArray($data, 0, $size - 1);
		echo " After Reverse \n";
		$task->display($data, $size);
	}
}
Transformation::main(array());

Output

 Before Reverse
  1  2  7  3  4  5  8  9
 After Reverse
  9  8  5  4  3  7  2  1

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment