5

I have an array for example

$a = [1,2,3,4,5]; 

From this $a, how to take last one and set it first like [5,1,2,3,4] And how do I take last two arrays to make it like [4,5,1,2,3]

FluffyKitten
  • 13,824
  • 10
  • 39
  • 52
somebodytolove
  • 171
  • 1
  • 1
  • 12

6 Answers6

5

You can combine using array_pop(), which pops the last element of the array out, and array_unshift() to push it to the front of the array. You can create a simple function for this,

function array_pop_unshift($array) {
    array_unshift($array, array_pop($array));
    return $array;
}

Then use it as

$a = [1,2,3,4,5];
$new = array_pop_unshift($a);
print_r($new); // [5,1,2,3,4]

To continue shifting it, just call the function again until you're done, for instance through a for loop,

$a = [1,2,3,4,5];
for ($i = 0; $i < 2; $i++) {
    $new = array_pop_unshift($a);
}
print_r($new); // [4,5,1,2,3]
Qirel
  • 25,449
  • 7
  • 45
  • 62
2

If you want to avoid the cost of several array_unshift and array_pop, you can build a generator that plays with the array internal pointer. If you really need a result array, use iterator_to_array() to create it:

$a = range(1,5);

function rotate(&$array, $step = 1) {
    $length = count($array);
    
    end($array);
    
    while ($step--)
        prev($array);
    
    while ($length--) {
        next($array);
        if (key($array) === null)
            reset($array);
            
        yield current($array);
    }
}

print_r(iterator_to_array(rotate($a, 2))); // [4,5,1,2,3]

demo

Note that the rotate() generator uses a reference to avoid the array copy but doesn't modify the orginal array: it only moves the array pointer n times (where n is the array length) from the choosen position. When the array pointer is out of the array (key() returns null) the array pointer is reseted. In other words it stays efficient even with a large array and many rotations (what I have called "step" in the code).

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

to take last one and set it first This is known as right rotation.

And $k is the number of units the shifting should be. $a is the array.

for($x=0; $x < $k; $x++){

    //remove last element
    $last = array_pop($a);

    //push last element to the beginning
    array_unshift($a, $last);

}

array_pop() pops and returns the value of the last element of array, shortening the array by one element. https://www.php.net/manual/en/function.array-pop.php

array_unshift() prepends passed elements to the front of the array https://www.php.net/manual/en/function.array-unshift.php

You could create a function that takes two arguments $k(number of rotations), $a (the array) and returns the array after performing right rotation $k times.

function rotateRight($a, $k){
    for($x=0; $x < $k; $x++){
       //remove last element
       $last = array_pop($a);
       //push last element to the beginning
       array_unshift($a, $last);
    }
    return $a;
}

And then call it accordingly.

Example:

$a = [1,2,3,4,5]; 

$a_one_shift = rotateRight($a, 1);
//  [5,1,2,3,4]; 

$a_two_shift = rotateRight($a_one_shift, 1);
// [4,5,1,2,3];

Or you could pass 2 to directly get the array after two right rotations.

$a_new = rotateRight($a, 2);
// [4,5,1,2,3];
Aashish gaba
  • 1,726
  • 1
  • 5
  • 14
1

You are actually doing right rotation, not left. Anyway, here are functions for doing both of them. They are probably not the most efficient but they are short in code and pretty self-explanatory:

<?php
    function rotateLeft($array, $times) {
        for($i=0; $i<$times; $i++){
            $array[] = array_shift($array);
        }
        return $array;
    }
    
    function rotateRight($array, $times) {
        for($i=0; $i<$times; $i++){
            array_unshift($array, array_pop($array));
        }
        return $array;
    }
    
    $a = [1,2,3,4,5]; 
    $a = rotateRight($a, 1);
    print_r($a);
?>
Philip Petrov
  • 975
  • 4
  • 8
1

Rather than making iterated calls of array_pop() and array_unshift(), use an efficient, elegant approach that makes fewer function calls and has the lowest possible time complexity. Using early returns prevents making needless function calls for the same result.

Code: (Demo)

function popUnshift(array $indexedArray, int $popShiftsCount): array
{
    $count = count($indexedArray);
    if ($count < 2) {
        return $indexedArray; // array cannot be rotated
    }
    $remainder = $popShiftsCount % $count;
    if (!$remainder) {
        return $indexedArray; // sought rotation is the original order
    }
    return array_merge(
        array_splice($indexedArray, -$remainder),
        $indexedArray
    );
}

Disclosure: This answer was built on the CodeReview page (Codility cyclic rotation solution in PHP) where I offered this snippet in my review.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

//$A input array, $K rotation times

function solution($A, $K) {
$new = array();
for($j=1;$j<=$K;$j++)
  {
    if(count($new)>0)
        $A = $new;
    for($i=0;$i<count($A);$i++)
      {
        if($i==0)
            $new[$i] = $A[count($A)-1];
        else
            $new[$i] = $A[$i-1];
      }
  }
return $new;}
Joy Chowdhury
  • 153
  • 1
  • 11