user759235
user759235

Reputation: 2207

Move array element with specific key to beginning of array

I could not find something about this, probably I missed it, but I want to filter/sort an array which has an key which I want to move to the top, so it will be the first item. In my example I want the key 3 to move to the top. Is there a simple way to do this?

// at default
[    
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 3" : [ some data ],// for this example I want this to be the first item
"key 4" : [ where is the data ]
]

// how i want it to be

move_to_first_in_array($array , 'key 3');

[  
"key 3" : [ some data ],// for this example I want this to be the first item  
"key 1" : [ more data ],
"key 2" : [ even more data ],
"key 4" : [ where is the data ]
]

Upvotes: 0

Views: 432

Answers (3)

Rushi Shukla
Rushi Shukla

Reputation: 46

Try also core PHP in This way.

<?php

$array = array(    
"key 1" => " more data ",
"key 2" => "even more data",
"key 3" => "some data ",// for this example I want this to be the first item
"key 4" => "where is the data"
);
echo "<pre>";print_r($array);
echo "<br>";


$array2 = array("key 3","key 1","key 2","key 4");

$orderedArray = array();
foreach ($array2 as $key) {
    $orderedArray[$key] = $array[$key];
}

echo "<pre>";print_r($orderedArray);exit;

?>

ANSWER :

Array
(
    [key 1] =>  more data 
    [key 2] => even more data
    [key 3] => some data 
    [key 4] => where is the data
)

Array
(
    [key 3] => some data 
    [key 1] =>  more data 
    [key 2] => even more data
    [key 4] => where is the data
)

Upvotes: 0

iainn
iainn

Reputation: 17417

function move_to_first_in_array($array, $key) {
  return [$key => $array[$key]] + $array;
}

This uses the + operator to return the union of the two arrays, with elements in the left-hand operand taking priority. From the documentation:

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

See https://3v4l.org/ZQV2i

Upvotes: 4

kalehmann
kalehmann

Reputation: 5011

How about:

function move_to_first_in_array(&$array, $key)
{
    $element = $array[$key];
    unset($array[$key]);
    $array = [$key => $element] + $array;
}

It is really ugly, but it works.

Upvotes: 0

Related Questions