Aparistar Aparistar - 3 months ago 13
PHP Question

Replace one arrays keys with another arrays values in php

I want to map form fields to database fields.

I have two arrays..

One array is the data and contains the form field id as the key and the form field value as the value.

$data = array("inputEmail"=>"someone@somewhere.com","inputName"=>"someone"... etc


I also have an array which i intended to use as a map. The keys of this array are the same as the form fields and the values are the database field names.

$map = array("inputEmail"=>"email", "inputName"=>"name"... etc


What i want to do is iterate over the data array and where the data key matches the map key assign a new key to the data array which is the value of the map array.

$newArray = array("email"=>"someone@somewhere.com", "name"=>"someone"...etc


My question is how? Ive tried so many different ways im now totally lost in it.

Answer

This is made quite nice with a foreach loop

foreach( $data as $origKey => $value ){
  // New key that we will insert into $newArray with
  $newKey = $map[$origKey];
  $newArray[$newKey] = $value;
}

A more condensed approach (eliminating variable used for clarification)

foreach( $data as $origKey => $value ){
  $newArray[$map[$origKey]] = $value;
}
Comments