how to change the order of values in a php array [duplicate]
Solution 1:
$numbers = array(1,2,3,4);
array_push($numbers, array_shift($numbers));
print_r($numbers);
Output
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 1
)
Solution 2:
Most of the current answers are correct, but only if you don't care about your indices:
$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
array_push($arr, array_shift($arr));
print_r($arr);
Output:
Array
(
[baz] => qux
[wibble] => wobble
[0] => bar
)
To preserve your indices you can do something like:
$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
$keys = array_keys($arr);
$val = $arr[$keys[0]];
unset($arr[$keys[0]]);
$arr[$keys[0]] = $val;
print_r($arr);
Output:
Array
(
[baz] => qux
[wibble] => wobble
[foo] => bar
)
Perhaps someone can do the rotation more succinctly than my four-line method, but this works anyway.
Solution 3:
It's very simple and could be done in many ways. Example:
$array = array( 'a', 'b', 'c' );
$array[] = array_shift( $array );
Solution 4:
A method to maintain keys and rotate. using the same concept as array_push(array, array_shift(array)), instead we will use array_merge of 2 array_slices
$x = array("a" => 1, "b" => 2, "c" => 3, 'd' => 4);
To move the First element to the end
array_merge(array_slice($x, 1, NULL, true), array_slice($x, 0, 1, true)
//'b'=>2, 'c'=>3, 'd'=>4, 'a'=>1
To move the last element to the front
array_merge(array_slice($x, count($x) -1, 1, true), array_slice($x, 0,
//'d'=>4, 'a'=>1, 'b'=>2, 'c'=>3