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

How to Rotate Array Elements to the Left in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 17:11:02479browse

How to Rotate Array Elements to the Left in PHP?

Rotating Array Elements to the Left in PHP

PHP provides a simple and effective way to "rotate" an array, meaning to move the first element to the last and renumber the indices accordingly. This can be achieved using the array_push() and array_shift() functions.

Example:

Suppose we have an array $numbers with the values 1, 2, 3, and 4. To rotate it to the left, we can use the following code:

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

print_r($numbers);</code>

Output:

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

Explanation:

  1. The array_shift() function removes the first element from the $numbers array and returns its value. In this case, it removes 1 and returns it.
  2. The array_push() function adds the specified value to the end of the $numbers array. In this case, it adds the value returned by array_shift() (which is 1) to the end of the array.
  3. The result is that the first element of the array is now 2, followed by 3, 4, and finally 1.

The above is the detailed content of How to Rotate Array Elements to the 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