3

I have a PHP array that has literal_key => value. I need to shift the key and value off the beginning of the array and stick it at the end (keeping the key also).

I've tried:

$f = array_shift($fields);
array_push($fields, $f);

but this loses the key value. Ex:

$fields = array ("hey" => "there", "how are" => "you");

// run above

this yields:

$fields = array ("how are" => "you", "0" => "there");

(I need to keep "hey" and not have 0) any ideas?

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Adam Esterle
  • 343
  • 2
  • 4
  • 13

2 Answers2

4

As far as I can tell, you can't add an associative value to an array with array_push(), nor get the key with array_shift(). (same goes for pop/push). A quick hack could be:

$fields = array( "key0" => "value0", "key1" => "value1");
//Get the first key
reset($fields);
$first_key = key($fields);
$first_value = $fields[$first_key];
unset($fields[$first_key]);

$fields[$first_key] = $first_value;

See it work here. Some source code taken from https://stackoverflow.com/a/1028677/1216976

Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • Shorter: `reset($fields); list($k, $v) = each($fields); unset($fields[$k]); $fields[$k] = $v;` – goat Aug 05 '12 at 16:49
2

You could just take the 0th key $key using array_keys, then set $value using array_shift, then set $fields[$key] = $value.

Or you could do something fancy like

array_merge( array_slice($fields, 1, NULL, true),
             array_slice($fields, 0, 1, true)     );

which is untested but has the right idea.

not all wrong
  • 622
  • 7
  • 18