Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi guys i would like to add a new item to an array but i want it to be an associative array... how do i accomplish this?

Let say i have a variable $arrayContainer.
Now i have a data of cities like "United State" = "UN", "Philippines" = "PH", now i want when i get the value $arrayContainer["UN"] this will output "United State"... how do i accomplish that? and also what if i would like to add another associative value let say i decided that i want to add the key "UAE" to display "United Arab Emirates"... How do i accomplish this?

I was thinking like this

PHP
$array["city"] = array('cebu' => 'c', 'davao' => 'd', 'manila' => 'm', 'zamboanga' => 'z');

array_push('radio' => 'r',$array["city"] );
echo $array["city"]["radio"];



Thanks in advance guys
Posted
Updated 30-Nov-11 21:07pm
v2
Comments
LanFanNinja 1-Dec-11 3:55am    
Check solution

1 solution

Well I am not sure I understand your question and it has been a while since I used PHP but is this what your looking for.

for associative array of associative arrays.
PHP
$container = array('country' => array('US'  => 'United States'));
$container['country']['UN'] = 'United Nations';
$container['country']['PH'] = 'Philippines';
echo $container['country']['US'];
echo $container['country']['UN'];
echo $container['country']['PH'];


for single associative array
PHP
$countries = array('UN' => 'United Nations');
$countries['US'] = 'United States';
$countries['PH'] = 'Philippines';
echo $countries['UN'];
echo $countries['US'];
echo $countries['PH'];


EDIT: you could even get crazy if you wanted and do something like this. :)
PHP
$countries = array('UN' => 'United Nations');
$countries['US'] = 'United States';
$countries['PH'] = 'Philippines';
$countries['other_countries'] = array('PL' => 'Poland');
$countries['other_countries']['RO'] = 'Romania';
echo $countries['UN'];
echo $countries['US'];
echo $countries['PH'];
echo $countries['other_countries']['PL'];
echo $countries['other_countries']['RO'];
 
Share this answer
 
v3
Comments
Madzmar25 1-Dec-11 4:33am    
Nice answer this is exactly what im looking for... thanks for the reply and sorry if my question wasnt clear enough... thanks again and more power
LanFanNinja 1-Dec-11 4:37am    
You're welcome

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900