2

Im trying to move an array item to the top of the array using unshift but I get an unexpected result:

$all_people = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
   $new_value = $all_people['Ben'];
   array_unshift($all_people, $new_value);

Here I expect to have an array where "Ben"=>"37 is the first item but I end up with this:

array(4) { [0]=> int(0) [1]=> string(5) "Peter" [2]=> string(3) "Ben" [3]=> string(3) "Joe" }

The first element is empty and "Ben" has not moved to the top which I thought was going to happen. Can someone help me out? Thanks!

6
  • 2
    $new_value is just "37", where do you expect "Ben" to come from? Commented Apr 18, 2018 at 14:00
  • If you're trying to unshift $all_people['Ben'] onto the array, you'll just end up inserting 37, without removing the original. If you want to sort an array, use the many sorting functions available. Commented Apr 18, 2018 at 14:01
  • 3
    Possible duplicate of How can I sort arrays and data in PHP? Commented Apr 18, 2018 at 14:02
  • Ok, i Thought $all_people['Ben'] would give me the "complete" item (including the key)...Any tips on how to do that? Commented Apr 18, 2018 at 14:02
  • Do you have a more practical example of what you're trying to do here? Obviously 'Ben' won't be hardcoded in your actual use case I assume…? Commented Apr 18, 2018 at 14:04

2 Answers 2

5

Try php array union operator for this:

$all_people = array('Ben' => $all_people['Ben']) + $all_people;

The first value in the union will always be first and duplicate keys will be automatically unset. So this takes care of everything in one shot.

You could also make this in to a function if it's something you need frequently in your application:

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

$all_people = moveToTop($all_people,'Ben');
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the way to move any element to the first.

$all_people = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$ben["Ben"] = $all_people["Ben"];
$all_people = $ben + $all_people;

Live Demo

2 Comments

you don't need to unset() in the first demo, and you don't need array_unique() in the second.
@billynoah : you are right, I forget it will replaced.

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.