4

I don't really know how to decribe this problem, so I'm sorry if the title is a bit unclear.

I got an object with array fields. I got the name of these fields stored in a variable and I want to reach an element in one of those array fields. e.g.

$field_name = 'array_field';

$object = new stdClass();
$object->array_field= array('this', 'is', 'an', 'array);

I know i can access the array with $object->$field_name, but now I want to access a value by key in the array while accessing it with the $field_name variable. e.g.(that obviously does not work) $object->$field_name[0]

hakre
  • 193,403
  • 52
  • 435
  • 836
Barthje
  • 143
  • 2
  • 7

2 Answers2

14

I think, you should use something like the following:

$object->{$field_name}[0]

It's described in details in "Variable variables" section of PHP manual: http://www.php.net/manual/en/language.variables.variable.php

BTW, according to my experience, such way of fields manipulation may lead to code obscurity - I'd recommend to use associative arrays, if possible.

Kel
  • 7,680
  • 3
  • 29
  • 39
  • Thanks! Works like a charm. I guess I'm blind because I couldn't find it there or I just didn't know what to look for – Barthje Oct 23 '10 at 06:25
3

Try this:

$object->{$field_name}[0]
mellowsoon
  • 22,273
  • 19
  • 57
  • 75