Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1405
终归单人心
终归单人心 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:56

    You want to move one of the elements to the beginning. Let's say

    $old = array(
    'key1' =>'value1', 
    'key2' =>'value2', 
    'key3' =>'value3', 
    'key4' =>'value4');
    

    And you want to move key3 to the beginnig.

    $new = array();
    $new['key3'] = $old['key3']; // This is the first item of array $new
    foreach($old as $key => $value) // This will continue adding $old values but key3
    {
    if($key != 'key3')$new[$key]=$value;
    }
    

提交回复
热议问题