w3resource

PHP Exercises: Shift an element in left direction and return a new array


124. Shift Array Elements Left

Write a PHP program to shift an element in left direction and return a new array.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{ 
    // Calculate the size of the input array
    $size = sizeof($numbers);

    // Initialize an array to store the shifted numbers
    $shiftNums = [$size];

    // Iterate through the elements of the input array using a for loop
    for ($i = 0; $i < $size; $i++)
    {
        // Shift the numbers to the left by one position, considering the circular nature of the shift
        $shiftNums[$i] = $numbers[($i + 1) % $size];
    }

    // Return the array of shifted numbers
    return $shiftNums;
}   

// Call the 'test' function with an example array and store the result in the variable 'result'
$result = test([10, 20, -30, -40, 50] );

// Print the result array as a string
echo "New array: " . implode(',', $result);
?>

Sample Output:

New array: 20,-30,-40,50,10 

Flowchart:

Flowchart: Shift an element in left direction and return a new array.

For more Practice: Solve these Related Problems:

  • Write a PHP script to create a new array by shifting all elements one position to the left, moving the first element to the end.
  • Write a PHP function to perform a left rotation on an array and return the resulting array.
  • Write a PHP program to simulate cyclic left rotation of an array using a temporary variable.
  • Write a PHP script to implement a left-shift algorithm that moves the head element to the tail of the array.

Go to:


PREV : Contains Three Increasing Adjacent Numbers.
NEXT : Array Elements Before Value 5.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.