1

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??

1
  • 1
    Array key name can't same for all .Here name,age repeating. use subarray Commented Jan 7, 2014 at 9:32

5 Answers 5

6

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 />';
}
Sign up to request clarification or add additional context in comments.

1 Comment

In this way, how can I get the values using foreach?
2
$a = array();
array_push($a, array("name"=>"n1","age"=>"age1"));
array_push($a, array("name"=>"n2","age"=>"age2"));

array_push

Comments

1
$a = array();
$a["name"][]= "n1";
$a["age"][]= "age1";
$a["name"][]= "n2";
$a["age"][]= "age2";

3 Comments

Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful.
@A.Singh What are you talking about?
This generates different result. Thank you anyway ;)
1

You can do by this way

$a = array(
  array(
      'name' => 'n1',
      'age'  => 'age1'
  ),
  array(
      'name' => 'n2',
      'age'  => 'age2'
  )
);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.