0

I have an array that I access like this:

$item['id'];

What can I do to the array to access it like this instead?

$item->id
1
  • 1
    $item->name isn't a reference to an associative array, you already have that.... it's an object reference Commented Mar 4, 2013 at 14:40

4 Answers 4

11

Use this code:

$item = (object) $item;
echo $item->property;

The -> syntax is for objects, not associative arrays. You can use the (object) cast operator to cast an array into an object of the class stdClass though.

Sign up to request clarification or add additional context in comments.

Comments

2

Cast it to (a stdClass) object:

$item = (object) $item;

Comments

1

If that array is coming from a database, such as mysql you can fetch objects instead of arrays with mysql_fetch_object() or set the flag PDO::FETCH_OBJ if you are using PDO.

Maybe it is not relevant to you however ...

Comments

0

You need to convert it into an object

$item = (object) $item;
echo $item->id;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.