0

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"]

3 Answers 3

4

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

1 Comment

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
0

Do it like this:

$obj->odp[0]['cool']

Comments

0

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

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.