Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do i merge two arrays? 1

Status
Not open for further replies.

benedictbutlin

Technical User
Oct 12, 2012
16
GB
i have 2 arrays 'my_names' and 'my_values'

my_names: Array
(
[0] => apple
[1] => peach
[2] => pear
[3] => banana
)

my_values: Array
(
[0] => red
[1] => pink
[2] => green
[3] => yellow
)

how would i merge them so values from 'my_name" become the keys for 'my_values', like so...

Array
(
[apple] => red
[peach] => pink
[pear] => green
[banana] => yellow
)

cheers!
 
that's not really merging an array in the sense of a php merge.

programmatically this would work
Code:
function mergeArrays($keys, $values){
 if(!is_array($keys) || !is_array($values)) return false;
 if(count($keys) !== count($values)) return false;
 $return = array();
 foreach($keys as $i=>$val) $return[$val] = $values[$i];
 return $return;
}

more properly, however, this is known as array "combining" and php has a built in function that should work

Code:
$newArray = array_combine($keys, $values);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top