简体   繁体   中英

PHP unshift associative array by the key

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!

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');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM