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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Shorter: reset($fields); list($k, $v) = each($fields); unset($fields[$k]); $fields[$k] = $v;
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.