0

I have a array

Array ( [0] => elem0 [1] => elem1 [2] => elem2 [3] => elem3 [4] => elem4 )

I want take the two last element from array and deplace in begin of that array.

To obtain :

Array ( [0] => elem3 [1] => elem4 [2] => elem0 [3] => elem1 [4] => elem2 )

in PHP.

Edit

I found :

$pkeys= Array ( [0] => elem0 [1] => elem1 [2] => elem2 [3] => elem3 [4] => elem4 );
$output = array_slice($pkeys, -2, 2);
array_splice($pkeys, -2, 2);
$pkeys=array_merge($output,$pkeys);   
print_r ($pkeys);

result :

 Array ( [0] => elem3 [1] => elem4 [2] => elem0 [3] => elem1 [4] => elem2 )

It's OK!

user2267379
  • 1,067
  • 2
  • 10
  • 20
  • possible duplicate of [PHP: 'rotate' an array?](http://stackoverflow.com/questions/5601707/php-rotate-an-array) – dostrander Aug 28 '13 at 01:51

2 Answers2

0

Use array_pop() and array_unshift().

Example:

$stack = array("orange", "banana", "apple", "raspberry");
$last_element = array_pop($stack);
array_unshift($stack, $last_element);
print_r($stack);

PHP has many array functions. Take the time to browse them.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

A lot of solution can do this , here is one possibility :

array_unshift($yourArray,$yourArray[count($yourArray)-2],$yourArray[count($yourArray)-1]);

array_pop($yourArray);

array_pop($yourArray);
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44