0

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 ]
]
9
  • 1
    You must provide the condition with which you want to filter your array Commented Sep 28, 2018 at 10:32
  • no its not a duplicate Commented Sep 28, 2018 at 10:34
  • @user759235 but why isn't it ... it's what you want? Commented Sep 28, 2018 at 10:34
  • I provided a example now Commented Sep 28, 2018 at 10:36
  • @user759235 that's what the linked question does? Commented Sep 28, 2018 at 10:37

3 Answers 3

4
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

Sign up to request clarification or add additional context in comments.

1 Comment

You were a bit quicker, so I removed my answer (saying basically the same thing) again ;-)
0

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.

Comments

0

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.