ThomasNorth Posted February 2, 2012 Share Posted February 2, 2012 Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. Link to comment https://forums.phpfreaks.com/topic/256238-associative-array-values-as-keys-for-associate-array/ Share on other sites More sharing options...
silkfire Posted February 2, 2012 Share Posted February 2, 2012 Sure there is. Use array_combine(keys, values) to create the new array. array_combine($array_with_values, $values); Link to comment https://forums.phpfreaks.com/topic/256238-associative-array-values-as-keys-for-associate-array/#findComment-1313614 Share on other sites More sharing options...
ThomasNorth Posted February 2, 2012 Author Share Posted February 2, 2012 Hiya Silkfire, Thanks for getting back to me. Just to clarify if anyone else happens to have a similar question, array_combine was applied in this context by doing: $new_element = array_combine(array_keys($item), $item); Cheers Silkfire! D. Link to comment https://forums.phpfreaks.com/topic/256238-associative-array-values-as-keys-for-associate-array/#findComment-1313628 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.