-1

I have an array of elements like this:

$data = array(1, 2, 3, 4);

How can I reorder for example, starting from second element to get 2, 3, 4, 1; or starting from third element to get 3, 4, 1, 2?

Salman A
  • 262,204
  • 82
  • 430
  • 521
notsoeasy
  • 41
  • 1
  • 9
  • `$data = array(2,3,4,1);`? What's the logic behind 2,3,4,1? First element becomes the last element? – brombeer Mar 22 '21 at 11:38
  • Yes exactly! If I want third element to be first , then second element should be last, so: 3,4,1,2. – notsoeasy Mar 22 '21 at 11:40
  • 3
    Does this answer your question? [PHP: 'rotate' an array?](https://stackoverflow.com/questions/5601707/php-rotate-an-array) – NoOorZ24 Mar 22 '21 at 11:46
  • @NoOorZ24 somehow yes. But that works only for one shifted element. if I want to shift like 2 ,3 elements like for example 4,1,2,3 then it doesn't work! – notsoeasy Mar 22 '21 at 12:06

3 Answers3

2

One solution is to use array_slice function to separate the two portions and combine them with array_merge:

$data = [1, 2, 3, 4];
$pos = 2;
$ordered = array_merge(
    array_slice($data, $pos),
    array_slice($data, 0, $pos)
);
// [3, 4, 1, 2]
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

You can use array_splice

$data = array(1,2,3,4);

$out = array_splice($data, 1, 3);
array_splice($data, 0, 0, $out);

print_r($data);
dajmund
  • 82
  • 5
-1

You could just array_shift() and then push the shifted value back on to the end of the Array:

$data = array(1,2,3,4);
$data[] = array_shift($data);
esqew
  • 42,425
  • 27
  • 92
  • 132