0

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!

billynoah
  • 17,021
  • 9
  • 67
  • 90
louis9898
  • 35
  • 5
  • 2
    `$new_value` is just `"37"`, where do you expect `"Ben"` to come from? – deceze Apr 18 '18 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. – iainn Apr 18 '18 at 14:01
  • 3
    Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – iainn Apr 18 '18 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? – louis9898 Apr 18 '18 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…? – deceze Apr 18 '18 at 14:04
  • Well im actually just trying to move a specific item to the top of the array. The array in the example is simplified but its got a key and value so whatever works inthe example should do the job. Thank you! – louis9898 Apr 18 '18 at 14:06

2 Answers2

2

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');
billynoah
  • 17,021
  • 9
  • 67
  • 90
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

Niklesh Raut
  • 29,238
  • 9
  • 61
  • 94