Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1406
终归单人心
终归单人心 2020-12-10 02:52

I have a PHP array similar to this:

0 => \"red\",
1 => \"green\",
2 => \"blue\",
3 => \"yellow\"

I want to move yellow to index

12条回答
  •  一个人的身影
    2020-12-10 03:49

    In case someone still looking for an answer, here is an alternate way.

    $colors = array("red","green","blue","yellow");
    $color_to_move = ["yellow"];
    $colors_wo_yellow = array_diff($colors, $color_to_move);// This will give an array without "yellow"
    //Now add "yellow" as 1st element to $
    array_unshift($colors_wo_yellow,$color_to_move[0]);
    

    That's it. :)

提交回复
热议问题