Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving array element to top in PHP

$arr = array(
    'a1'=>'1',
    'a2'=>'2'
);

I need to move the a2 to the top, as well as keep the a2 as a key how would I go on about it I can't seem to think a way without messing something up :)

like image 862
Val Avatar asked Mar 15 '11 14:03

Val


People also ask

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is the use of Array_unshift () function?

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like. Note: Numeric keys will start at 0 and increase by 1.

How do you move an element in an array?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.


1 Answers

try this:

$key = 'a3';
$arr = [
    'a1' => '1',
    'a2' => '2',
    'a3' => '3',
    'a4' => '4',
    'a5' => '5',
    'a6' => '6'
];
if (isset($arr[ $key ]))
    $arr = [ $key => $arr[ $key ] ] + $arr;

result:

array(
    'a3' => '3',
    'a1' => '1',
    'a2' => '2',
    'a4' => '4',
    'a5' => '5',
    'a6' => '6'
)
like image 179
jalmatari Avatar answered Nov 16 '22 01:11

jalmatari