How to add an array value to the middle of an associative array?

前端 未结 13 1637
余生分开走
余生分开走 2020-12-08 00:36

Lets say I have this array:

$array = array(\'a\'=>1,\'z\'=>2,\'d\'=>4);

Later in the script, I want to add the value \'c\'=>3<

13条回答
  •  既然无缘
    2020-12-08 01:33

    Try this

    $array['c']=3;
    

    An associative array is not ordered by default, but if you wanted to sort them alphabetically you could use ksort() to sort the array by it's key.

    If you check out the PHP article for ksort() you will se it's easy to sort an array by its key, for example:

    "lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
    ksort($fruits);
    foreach ($fruits as $key => $val) {
        echo "$key = $val\n";
    }
    ?>
    
    // The above example will output:
    a = orange
    b = banana
    c = apple
    d = lemon
    

提交回复
热议问题