Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one arrays keys with another arrays values in php

Tags:

arrays

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.

like image 730
Aparistar Avatar asked Mar 31 '13 22:03

Aparistar


People also ask

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How do you change the key of an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.

How do you remove an array from a key?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.


2 Answers

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;
}
like image 80
Sam Lanning Avatar answered Nov 03 '22 01:11

Sam Lanning


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
)
like image 28
Imran Zahoor Avatar answered Nov 03 '22 00:11

Imran Zahoor