aspirinemaga
aspirinemaga

Reputation: 3947

Updating a PHP array of POST datas, before processing them

I need to apply some functions to a key items inside an array before moving on with the whole array, but I probably miss something.
Here is my code:

// Get generated datas
$data_post = $this->input->post('form_data'); // Need to update this array

foreach( $data_post as $data ){
    $data['password'] = password_encrypt($data['password']);
    var_dump($data); // Password encryption succeed
}

var_dump($data_post); // But here, the password is still the same, no encryption applied

So as commented in the CODE section, how should I update the main $data_post array with the modifications made in foreach() ?

Upvotes: 0

Views: 57

Answers (2)

Vijay Verma
Vijay Verma

Reputation: 3698

Try this:

$data_post = $this->input->post('form_data'); // Need to update this array


foreach( $data_post as $k=>$v ){
      if($k == "password"){
          $data_post[$k] = password_encrypt($v);
      }
 }

var_dump($data_post);

Upvotes: 0

Vlad Preda
Vlad Preda

Reputation: 9920

Inside a foreach, data isn't passed by reference. This means that modifying the variable $data doesn't modify $data_post. You can modify the original array in more than one way, but here is how I would do it:

foreach( $data_post as $key => $data ){
    $data_post[$key]['password'] = password_encrypt($data['password']);
}

Note that this presumes that $data_post contains multiple sub arrays, each with the password key (or else notices will be thrown).

Upvotes: 4

Related Questions