Skip to content
Advertisement

Php associative array value update from a form

I am trying to update value of an associative array from form data. When the user presses submit, the array values should be updated. Here is the code below.

$userInfo = array('new_user_name' => '',
                  'new_user_email'=>'',
                  'new_user_mobile'=>'',
                  'new_user_area'=>'',
                  'new_user_address'=>'');



if (isset($_POST['submit-add-user'])) {

    foreach($userInfo as $key => $value){
   $key['new_user_name'] = $_POST['name'] ;
   $key['new_user_email'] = $_POST['email'];
   $key['new_user_mobile'] = $_POST['mobile'];
   $key['new_user_area'] = $_POST['area'];
   $key['new_user_address'] = $_POST['address'];
    }
   
   
}

How can I do this?

Advertisement

Answer

This might help you refine your question.

Use the same keys, with different array names.

This would just assign a subset of posted form values to a new array if given:

<?php

$form_fields = ['name', 'email', 'mobile', 'area', 'address'];

$dirty = [];
foreach($form_fields as $name) {
    $dirty[$name] = $_POST[$name] ?? null;
}

If you want to compare changes in simple arrays:

$before = [
    'name'  => 'Peggy',
    'email' => 'peggy@example.com'
];

$after = [
    'name'  => 'Peter',
    'email' => 'peggy@example.com'
];

var_export(array_diff_assoc($after, $before));

Output:

array ( 'name' => 'Peter', )
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement