0

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()'?

1

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

At the risk of appearing to want to be fed everything, I don't have any sort logic apart from simply wanting to pass a key and have that key (plus associated value) move to the first index position. Can you help with that?
@Dayo I wrote the some_func for your requirement :)
PHP's sort algorithm is not stable, so using it isn't very trivial for this case. You'd have to index every element before sorting so that you could preserve order. A non-sort answer is likely to be the most efficient.
You should check for key If key is not exist then it will add key at first position but value will be not available.
@xdazz Thanks for the modified version. It is similar to Mahesh's answer which I accepted as it came earlier.
1

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;        
    }
}

Comments

1
function some_func($arr, $key) {
    $val = $arr[$key];
    unset($arr[$key]);
    return array_merge(array($key => $val), $arr);
}

See it on codepad

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.