Reputation: 33
I'm tring to add new values to an associative array dynamically and I need your help. Here is a simple example :
$a = array();
$a["name"]= "n1";
$a["age"]= "age1";
$a["name"]= "n2";
$a["age"]= "age2";
The result is: Array (2){["name"]=>string(2) "n2" ["age"]=>string(4) "age2" }
I want to add The first age and name and the second age and name to the array. What can I do??
Upvotes: 1
Views: 108
Reputation: 4288
If you want to maintain name <=> age relationship :
$a = array();
$a[] = array("name"=>"n1","age"=>"age1");
$a[] = array("name"=>"n2","age"=>"age2");
UPDATE : usage example below :
foreach ($a as $assoc) {
echo $assoc["name"],' is ',$assoc["age"],'.<br />';
}
Upvotes: 6
Reputation: 48711
That's very easy and simple, you can do whatever you want with arrays!! Any doubts? Here you go:
$a = array();
if(is_array($a) && i_can_answer())
{
$keys = array('age', 'name');
$anotherArray = array();
if(is_array($anotherArray ) && i_know_multi_dimensional_arrays())
{
array_push($anotherArray, array("+18", "ILovePHP"));
$result1 = array_combine($keys, $anotherArray);
}
$otherAnotherArray = array();
if(is_array($otherAnotherArray) && i_am_not_tired())
{
array_push($otherAnotherArray , array("+18", "ILovePHP"));
$result2 = array_combine($keys, $otherAnotherArray);
}
$a = array_merge($result1, $result2);
}
print_r($a); //// hoooorrraaaaaaaaaay
Upvotes: 1
Reputation: 3647
$a = array();
array_push($a, array("name"=>"n1","age"=>"age1"));
array_push($a, array("name"=>"n2","age"=>"age2"));
Upvotes: 2
Reputation: 2597
You can do by this way
$a = array(
array(
'name' => 'n1',
'age' => 'age1'
),
array(
'name' => 'n2',
'age' => 'age2'
)
);
Upvotes: 1
Reputation: 8020
$a = array();
$a["name"][]= "n1";
$a["age"][]= "age1";
$a["name"][]= "n2";
$a["age"][]= "age2";
Upvotes: 1