Prakash Raman
Prakash Raman

Reputation: 13923

Convert associative array elements to object only

My array

$arr = array(
  "name" => "Prakash",
  "tall" => "maybe",
  "nick_names" => array ("p", "b", "bee", "prak", "new_names" => array("short_name" =>   "sn", "long_name" => "ln"))
);

I want to be able to create an object from which the values can be accessed via attributes.

e.g.

 $obj->name // "PRAKASH"
 $obj->nick_names // array("p", "b", "bee", "prak", "new_names" => (object))

How could I get this ?

I seem to able to accomplish exactly what I need through

$obj = json_decode(json_encode($arr));

But obviously that is not the right thing to do.

Thanks.

Upvotes: 1

Views: 3199

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174937

You can cast it into an stdClass:

$obj = (stdClass) $arr;

Take note that in PHP an array is far superior to an stdClass in any thinkable way.

  • Better performance
  • Better traversing abilities
  • Better readability (IMO)

Upvotes: 2

Related Questions