Push item to associative array in PHP

后端 未结 12 1328
野趣味
野趣味 2020-12-04 22:47

I\'ve been trying to push an item to an associative array like this:

$new_input[\'name\'] = array(
    \'type\' => \'text\', 
    \'label\' => \'First          


        
相关标签:
12条回答
  • 2020-12-04 23:38

    You can try.

    $options['inputs'] = $options['inputs'] + $new_input;
    
    0 讨论(0)
  • 2020-12-04 23:40

    Instead of array_push(), use array_merge()

    It will merge two arrays and combine their items in a single array.

    Example Code -

    $existing_array = array('a'=>'b', 'b'=>'c');
    $new_array = array('d'=>'e', 'f'=>'g');
    
    $final_array=array_merge($existing_array, $new_array);
    

    Its returns the resulting array in the final_array. And results of resulting array will be -

    array('a'=>'b', 'b'=>'c','d'=>'e', 'f'=>'g')
    

    Please review this link, to be aware of possible problems.

    0 讨论(0)
  • 2020-12-04 23:42

    WebbieDave's solution will work. If you don't want to overwrite anything that might already be at 'name', you can also do something like this:

    $options['inputs']['name'][] = $new_input['name'];

    0 讨论(0)
  • 2020-12-04 23:42

    i use php5.6

    code:

    $person = ["name"=>"mohammed", "age"=>30];
    
    $person['addr'] = "Sudan";
    
    print_r($person) 
    

    output

    Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )
    
    0 讨论(0)
  • 2020-12-04 23:43
    $new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
    $options['inputs']['name'] = $new_input;
    
    0 讨论(0)
  • 2020-12-04 23:49

    There is a better way to do this:

    If the array $arr_options contains the existing array.

    $arr_new_input['name'] = [
        'type' => 'text', 
        'label' => 'First name', 
        'show' => true, 
        'required' => true
    ];
    
    $arr_options += $arr_new_input;
    

    Warning: $arr_options must exist. if $arr_options already has a ['name'] it wil be overwritten.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题