Home >Backend Development >PHP Tutorial >How to Rotate Array Elements Left in PHP?

How to Rotate Array Elements Left in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 17:56:24421browse

How to Rotate Array Elements Left in PHP?

Reordering Array Elements through Left Rotation with PHP

The task of rotating array elements to the left, moving the first element to the last and updating indices, presents itself in programming contexts. For instance, suppose we have an array [1, 2, 3, 4] that we want to rotate. The result would be [2, 3, 4, 1].

Built-in PHP Function for Array Rotation

PHP does not provide a predefined function for array rotation. Hence, a custom approach is necessary.

Custom Rotation Method

The following code demonstrates a method for rotating an array in PHP:

<code class="php"><?php
$numbers = array(1,2,3,4);
array_push($numbers, array_shift($numbers));
print_r($numbers);
?></code>

Explanation

  • array_shift($numbers): Removes the first element from the array (1 in this case)
  • array_push($numbers, $first): Adds the removed element to the end of the array
  • The result is the original array with the first element rotated to the end

Output

The output of the script will be:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 1
)

The above is the detailed content of How to Rotate Array Elements Left in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn