PHP - Convert Array to Object with stdClass

The PHP stdClass() is something that isn't well documented but i will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. The name stdClass is used internally by Zend and is reserved. So that means that you cannot define a class named stdClass in your PHP code.

It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which expect to take an object as an argument. An even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.

Here's an example below that converts an array to an object below. This method is called Type Casting.

<?php
$person = array (
   'firstname' => 'Richard',
   'lastname' => 'Castera'
);

$p = (object) $person;
echo $p->firstname; // Will print 'Richard'
?>

Here's an example below that converts a multi-dimensional array to an object. This is accomplished through recursion.

<?php
function arrayToObject($array) {
	if(!is_array($array)) {
		return $array;
	}
   
	$object = new stdClass();
	if (is_array($array) && count($array) > 0) {
	  foreach ($array as $name=>$value) {
	     $name = strtolower(trim($name));
	     if (!empty($name)) {
	        $object->$name = arrayToObject($value);
	     }
	  }
      return $object; 
	}
    else {
      return FALSE;
    }
}
?>
<?php
$person = array (
   'first' => array('name' => 'Richard')
);

$p = arrayToObject($person);
?>
<?php
// Now you can use $p like this:
echo $p->first->name; // Will print 'Richard'
?>

43 comments for PHP - Convert Array to Object with stdClass

Noam's picture

Hey Richard, I really like...

Hey Richard, I really like your blog! It's great! Also Google ads are very smoothly integrated.

Richard's picture

Thanks!...

Thanks!

ivan's picture

$obj = new...


$obj = new ArrayObject($array);

TuVinhSoft's picture

Hi Richard. This is very...

Hi Richard. This is very useful function to convert Array to stdClass object.

Please check out with:


$person = array (
'first' => array('name' => array('first_name' => 'Richard', 'last_name' => 'Castera') )
);

Thanks

Blogo's picture

Great post! Just discovered...

Great post!
Just discovered that


$a = (object)mysql_fetch_assoc();

is faster than


$a = mysql_fetch_object();

marcelo toscano's picture

I really like this ... thanks...

I really like this ... thanks

Darryl Browne's picture

I was looking for something...

I was looking for something like this today and found your blog. While I couldn't get your solution to work (probably because I'm really tired at the moment Sad but it did inspire me to create my own version which I thought I would share:


public function makeObjects($data) {
$object = (object) $data;

foreach ($object as $property) {
if (is_array($property)) $this->makeObjects($property);
}

return $object;
}

Its a little more compact and easier to follow I think. You can also embellish and add in the strtolower and trim for the properties if you like.

Richard's picture

Darryl, Thanks for sharing...

Darryl, Thanks for sharing that!

Rob Apodaca's picture

You can also define your own...

You can also define your own class:


class arrayClass
{
public function __construct( $array = array() )
{
foreach( $array as $key => $value )
{
if( TRUE === is_array($value) )
$this->$key = new arrayClass( $value );
else
$this->$key = $value;
}
}
}

Then use it like this:


$array = array( 'a' => 'abc', 'b' => 'xyz', 'c' => array('one' => 1, 'two' => 2) );
$obj = new arrayClass( $array );
print $obj->c->one; //prints '1'

Terri Ann's picture

Great post Richard! I was...

Great post Richard! I was having a problem with a class I needed to serialize to store the value but I needed dynamic variables and stdClass kept erroring out saying:

Fatal error: Cannot access empty property

It didn't even occur that I should just create an assoc array and cast it to an object. Thanks for publishing this!

Richard's picture

Terri, I'm happy you found...

Terri, I'm happy you found this useful! Smile

Tworzenie Stron Warszawa's picture

Thanks for sharing that!...

Thanks for sharing that!

Richard's picture

Tworzenie, Sure!...

Tworzenie, Sure! Smile

Chang's picture

Very nice function...

Very nice function indeed,

However I'm having a problem at this moment, it seems that when I call the function to convert an multidimensional associate array, it chops off the first element in the converted stdobject

I'll let you know what I find out.

Richard's picture

Chang, Please do. Thanks!...

Chang,

Please do. Thanks!

JB's picture

settype($array,'object');...


settype($array,'object');

Richard's picture

JB, Thanks for sharing that!...

JB, Thanks for sharing that!

Laurie's picture

I too was having the same...

I too was having the same problem as Chang using this code where the first element of an multidimensional associate array was being lost.

The problem is in the test "!empty($name)". If the array uses numeric indices, index zero is considered empty.

I changed "!empty($name)" to "!is_null($name)" and conversion worked as expected.

Interesting, all the samples that I found on the web use the !empty test and would all fail to convert for zero index.

Hope this helps.

Richard's picture

Laurie, Thanks for sharing...

Laurie, Thanks for sharing that!

piwshop's picture

I'm trying to implement this...

I'm trying to implement this with CJ SOAP API, but I think CJ SOAP API is more complicated, I'm still not able to convert stdClass Object to Array.

Richard's picture

piwshop, Try reading a couple...

piwshop, Try reading a couple of the comments above, they might have a solution for you.

v's picture

stdClass is an internal class...

stdClass is an internal class name, not documented and so not recommended to use directly. it might even change in future php versions. instead, you should stick to converting arrays to object, or if you just need a blank object, convert a null to object.

Edward Savage's picture

v Who recommends against...

v Who recommends against using stClass? The Zend Framework uses it extensively, and it seems they'd have an inside track on such things.

Dave Edelhart's picture

With all due respect, many...

With all due respect, many frameworks like Drupal will come to a screaming halt if using stdClass directly is disallowed so I think its safe to say that stdClass will be a usable term for the foreseeable future.

Stas's picture

Buddy! You are best! I waste...

Buddy! You are best!
I waste 3 hr in looking for this.
Tnx very-very!

Richard's picture

Stas,...

Stas, Wink

Mikkel Juhl's picture

Hello Richard! Just got here...

Hello Richard!

Just got here from Google, I am currently working on something to do with the Twitter API and that makes a array and stuff. And this just helped me to get the most recent status, I am very grateful, for this! Thank you!

Webagentur's picture

Thank you, that has me very...

Thank you, that has me very helped.

Sag-e-Attar Junaid Atari's picture

Cool, this is what i was...

Cool, this is what i was looking for.

Man, Your the rock.

Yury's picture

I've made a similar solution...

I've made a similar solution and also a php extension that does that:
http://freebsd.co.il/cast/

Bill's picture

Very cool, Yury... seems like...

Very cool, Yury... seems like it's throwing a car instead of a wrench at this particular solution, but seeing yours, gave me another idea Wink. well done!

Edwin's picture

Hi maybe the following...

Hi maybe the following onliner-function is also a possible solution for some of you. It is part of a static method of a class named 'Type'. So it can be replaced by a global method if needed:


static public function array2Object($aArray)
{
return is_array($aArray) ? (object)array_map('Type::array2Object', $aArray) : $aArray;
}

And try to avoid the following mistake. It took me a moment to realize it when I made the mistake. An example:


$aTest = array('field1', 'field2', 'field3');
$oTestInt = Type::array2Object($aTest);
$oTestString = Type::array2Object(array_fill_keys($aTest, ''));

Make a choice what type of object-properties you want: integer ($oTestInt) or string ($oTestString).

john's picture

I found out another way. I...

I found out another way. I was looking for a way to reference the array returned from a function and happened on your post. As is turns out it is impossible in PHP to do what I wanted. Well, I FOUND A WORKAROUND, using your post and users' comments I was inspired. It's not elegant and probably has more CPU overhead. Hopefully it helps somebody who is trying to do the same thing I was.

Here's what I wanted to do:


<?php
print_r(get_defined_functions()['user']);
?>

Then I found your post on how to convert arrays to objects thinking that I could:


<?php
print_r(arrayToObject(get_defined_functions())->user);
?>

But that doesn't work in PHP. So finally I came up with:


<?php
print_r(json_decode(json_encode(get_defined_functions()))->user);
?>

SUCCESS!! I just don't know why there isn't a function to do this already. Perhaps the powers that be will copy the part of JSON handling that is converting the data to an object and make it into a built-in function. One can only hope. Thx for the post!

Anonymous's picture

Simple and awesome . Thanks...

Simple and awesome . Thanks

Curious Onlooker's picture

Great. Just what I was...

Great. Just what I was looking for, and thanks for the sharing.

What I'm after now, is something that does the reverse, lets me now work with that object as an array.

Laurent's picture

Works great, thanks!...

Works great, thanks!

James's picture

Just found this very useful...

Just found this very useful when using WordPress's native database access..

$example = $wpdb->get_results("SELECT * FROM `wp_posts` WHERE ID= '20'");
print_r($example);

returns something like

Array ( 0 => stdClass Object ([id] => 20, [post_name] => example, ...) )

trying to mimic that result from form data was doing my head in.. so thank you Smile

Deepa's picture

Nice work Richard! Was a...

Nice work Richard! Was a little bit confused about stdClass. Thank you!

FREAK's picture

It works, Thank you very...

It works, Thank you very much, Smile ..

Anonymous's picture

Hi great post was looking for...

Hi great post was looking for something like this however im stuck as cannot get the recursion properly working....

class config
{
function __construct() {}

function get_objects()
{
return get_object_vars($this);
}

public function make_objects($data)
{
$object = (object) $data;

foreach( $object as $key => $value )
{
if(is_array($value) )
{
$this->$key = (object) $value;//$this->make_objects( $value );
}
else
{
$this->$key = $value;
}
}
}

function test()
{
$arr = array(
'a' => 'test a',
'b' => array(
'b_arr' => 'test b',
'c' => array(
'c_arr' => 'test c'
)
)
);

$this->make_objects($arr);
}
}

if i print_r the config object i get... when not using the recursive method which fine except for the C ARRAY which is expected.

config Object ( [a] => test a [b] => stdClass Object ( [b_arr] => test b [c] => Array ( [c_arr] => test c ) ) )

however when i use the method as recursive i get...

config Object ( [a] => test a [b_arr] => test b [c_arr] => test c [c] => [b] => )

so i love the object after the first array and also adds some crap to the end Sad

any help would be greatly appreciated...

mehdi's picture

i used ypur code . and add...

i used ypur code .

and add that to my db
:

$array = array(
"title" => "Harry Potter and the Prisoner of Azkaban",
"author" => "J. K. Rowling",
"publisher" => "Arthur A. Levine Books",
"amazon_link" => "http://www.amazon.com/dp/0439136369/"
);

$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";

Shine's picture

I'd like to share my solution...

I'd like to share my solution using json with php 5.3 up
<?php
function arrayToObject($data) {
if(is_array($data)) {
$data = json_encode($data);
$data = json_decode($data);
return $data;
}else{
return $data;
}
}

function objectToArray($data){
if(is_array($data)) {
$data = json_encode($data);
$data = json_decode($data,true);
return $data;
}else{
return $data;
}
}
?>

Korvin's picture

What I always do to preserve...

What I always do to preserve multidimensionality is json_decode(json_encode());


<?php
$array = array("this"=>array("that","this"=>"then","those"),"them","test"=>"that");
print_r(json_decode(json_encode($array)));
?>

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.