Genjo
Genjo

Reputation: 123

Questions about array/associative array

i am trying to create a 3-level array then retrieve the 3th level array data but somehow i get this.

$project = array();
$project[] = "name";
$project[] = "id";
$project["id"] = "AXA";
$project["id"]["AXA"] = "a new project";
echo $project["id"]["AXA"];

The result i get is a which came from a new project

How do get the whole string?

Upvotes: 0

Views: 57

Answers (2)

zgr024
zgr024

Reputation: 1173

Your code should just use a multi-dimensional array as the assignment like the following

$project = array (
    'name',
    'id'=>array(
        'AXA'=>'a new project'
    ) 
);

Upvotes: 1

Kermit
Kermit

Reputation: 34054

Here's a var_dump of your code:

array(3) {
  [0]=>
  string(4) "name"
  [1]=>
  string(2) "id"
  ["id"]=>
  string(3) "aXA"
}

You're not actually creating a new level. What you need to do is initialize the 2nd array:

$project = array();
$project[] = "name";
$project[] = "id";
$project["id"] = array(); //here
$project["id"]["AXA"] = "a new project";

Otherwise, it will write over the value AXA.

array(3) {
  [0]=>
  string(4) "name"
  [1]=>
  string(2) "id"
  ["id"]=>
  array(1) {
    ["AXA"]=>
    string(13) "a new project"
  }
}

Upvotes: 0

Related Questions