Aparistar
Aparistar

Reputation: 185

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"=>"[email protected]","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"=>"[email protected]", "name"=>"someone"...etc

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

Upvotes: 6

Views: 11237

Answers (2)

Imran Zahoor
Imran Zahoor

Reputation: 2787

If you want to replace keys of one array with values of the other the solution is array_combine

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

print_r output

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

Upvotes: 10

Sam Lanning
Sam Lanning

Reputation: 636

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;
}

Upvotes: 12

Related Questions