views:

43

answers:

5

I want to access information in an associative array by index like so

$arr = Array(
    ['mgm19'] => Array(
        ['override'] => 1
    )
);

$override1 = $arr['mgm19']['override'];
$override2 = $arr[0]['override'];

but i get nothing from override2 why ?

+4  A: 

Because $arr has only one index, mgm19. Nothing is associated to the index 0. If you don't know the index or don't want to use it, use foreach:

  foreach($arr as $value) {
     echo $value['override'];
     break; /* breaking so that we only read the first value of the array */
  }
Alsciende
http://php.net/manual/en/language.types.array.php"The indexed and associative array types are the same type in PHP, which can both contain integer and string indices."I may be wrong, but doesn't that mean it should already contain a numeric index?
DavidYell
ok so how do i get to override if don't mgm19 is dynamic and I don't know what it's going to be ?
mcgrailm
@DavidYell: no, it means the index can be 0 and can be 'mgm19'. Here, the only index is 'mgm19'.@mcgrailm: see my completed answer
Alsciende
bummer I guess that'll have to do
mcgrailm
A: 

I would have a look at this function, http://www.php.net/manual/en/function.array-values.php which looks like it could be helpfull :)

DavidYell
+2  A: 

php.net/manual/en/language.types.array.php "The indexed and associative array types are the same type in PHP, which can both contain integer and string indices." I may be wrong, but doesn't that mean it should already contain a numeric index?

No, it's saying you can use both numeric and string indicies, not that you can access them using one or the other. Remember a key is a unique value identifier, and if you're allowed to use a number or a string you cannot access them using their numeric position in the array, take the following array:

$arr = Array(
   [mgm19] => Array(
    [override] => 1
   ),
   [0] => Array(
    [override] => 1
   )
);

We're allowed to have mixed datatypes as a key, and the reason you cannot access [mgm19] as [0] is because that's not its key.

I hope that made sense :P

ILMV
Yes, it does! I did think that too, but wasn't sure when I read the manual!
DavidYell
A: 

Associative arrays cannot be accessed using the numerical position in the array.

Technically, all arrays in PHP are the same. Each position in an array is defined with either a numerical value or a string, but not both.

If you want to retrieve a specific element in the array, but not use the associative index you have defined, then use the current, prev, next, reset, and end functions.

Joseph
+2  A: 
$arr = Array( 
    ['mgm19'] => Array( 
        ['override'] => 1 
    ) 
); 

$override1 = $arr['mgm19']['override']; 
$arrkeys = array_keys($arr);
$override2 = $arr[$arrkeys[0]]['override']; 
Mark Baker
I like this solution better
mcgrailm