Is there a PHP function to move an array key/value pair and make it to become the first element in the array.
Basically, I will like to convert
Array
(
[a] => rose
[b] => tulip
[c] => dahlia
[d] => peony
[e] => magnolia
)
to
Array
(
[c] => dahlia
[a] => rose
[b] => tulip
[d] => peony
[e] => magnolia
)
To clarify, the aim is to pick one specific key/value pair and move it to become the first indexed while keeping the rest of the order intact.
So in this case, I am looking for something like
$old_array = Array
(
[a] => rose
[b] => tulip
[c] => dahlia
[d] => peony
[e] => magnolia
);
$new_array = some_func($old_array, 'c');
In $new_array, 'c' should be first in the list.
Any ideas on code for 'some_func()'?
This may helpful to you :
function myfun($ar,$key){
if (array_key_exists($key,$ar)) {
$arr_tmp = array($key => $ar[$key]);
unset($ar[$key]);
return $arr_tmp + $ar;
}
}
If you only want to put one element to first, then you could do:
function some_func($array, $key) {
$tmp = array($key => $array[$key]);
unset($array[$key]);
return $tmp + $array;
}
function some_func($arr, $key) {
$val = $arr[$key];
unset($arr[$key]);
return array_merge(array($key => $val), $arr);
}