views:

94

answers:

3

If I have an object with an array as an attribute, what is the easiest way to access it?

$obj->odp = array("ftw", "pwn", array("cool" => 1337));

//access "ftw"
$obj->odp->0

//access 1337
$obj->odp->2->cool

This doesn't seem to work. Is there something I'm doing wrong, or do I have to first assign it to a variable?

$arr = $obj->odp;

//access "ftw"
$arr[0]

//access 1337
$arr[2]["cool"]
A: 

Do it like this:

$obj->odp[0]['cool']
Pim Jager
+4  A: 

Arrays can only be accessed with the array syntax ($array['key']) and objects only with the object syntax ($object->property).

Use the object syntax only for objects and the array syntax only for arrays:

$obj->odp[0]
$obj->odp[2]['cool']
Gumbo
are you sure you can access objects with the array syntax? I am trying to do that, and getting this error:Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\CUMF3\sites\all\modules\results\results.module on line 80
Rosarch
@Rosarch: Yeah, you’re right.
Gumbo
A: 

$obj->odp is an array, so $obj->odp[0] reads "ftw". There's no such thing like $obj->odp->0.

Havenard