Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP take array key and value from beginning and put at end

Tags:

arrays

php

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?

like image 506
Adam Esterle Avatar asked Feb 18 '26 18:02

Adam Esterle


2 Answers

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

like image 83
SomeKittens Avatar answered Feb 21 '26 15:02

SomeKittens


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.

like image 23
not all wrong Avatar answered Feb 21 '26 13:02

not all wrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!