w3resource

PHP Exercises: Rotate the elements of a given array of integers in left direction and return the new array

PHP Basic Algorithm: Exercise-90 with Solution

Write a PHP program to rotate the elements of a given array of integers (length 4 ) in left direction and return the new array.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that rotates the elements of the given array.
function test($a1)
{ 
    // Return a new array with elements rotated by one position to the left.
    return [$a1[1], $a1[2], $a1[3], $a1[0]];
}

// Create an array $a with initial values.
$a = [10, 20, -30, -40];

// Display the original array.
echo "Original array: " . implode(',', $a) . "\n";

// Call the 'test' function to rotate the array elements.
$result = test($a);

// Display the rotated array.
echo "Rotated array: " . implode(',', $result);
?>

Sample Output:

Original array: 10,20,-30,-40
Rotated array: 20,-30,-40,10

Flowchart:

Flowchart: Rotate the elements of a given array of integers in left direction and return the new array.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of the elements of an given array of integers.
Next: Write a PHP program to reverse a given array of integers and length 5.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.