Richard Castera

Application Developer/Designer
  • Home
  • About
  • Projects

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'
?>
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Don't forget to Subscribe and Follow!

Be sure to subscribe to the feed and follow me on Twitter for more insights and resources!

29 Responses to “PHP – Convert Array to Object with stdClass”

  1. Comment #1 - Permalink
    Noam
    07/07/2009

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

  2. Comment #2 - Permalink
    Richard
    07/07/2009

    Thanks!

  3. Comment #3 - Permalink
    ivan
    07/09/2009

    $obj = new ArrayObject($array);

  4. Comment #4 - Permalink
    TuVinhSoft
    07/09/2009

    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

  5. Comment #5 - Permalink
    Blogo
    07/09/2009

    Great post!
    Just discovered that
    $a = (object)mysql_fetch_assoc();
    is faster than
    $a = mysql_fetch_object();

  6. Comment #6 - Permalink
    marcelo toscano
    07/09/2009

    I realy like this … thanks

  7. Comment #7 - Permalink
    Darryl Browne
    07/30/2009

    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 :( ) 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 embelish and add in the strtolower and trim for the properties if you like.

  8. Comment #8 - Permalink
    Richard
    07/31/2009

    @Darryl, Thanks for sharing that!

  9. Comment #9 - Permalink
    Rob Apodaca
    08/14/2009

    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′

  10. Comment #10 - Permalink
    Terri Ann
    09/25/2009

    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!

  11. Comment #11 - Permalink
    Richard
    09/26/2009

    @terri, I’m happy you found this useful! :)

  12. Comment #12 - Permalink
    Tworzenie Stron Warszawa
    11/08/2009

    Thanks for sharing that!

  13. Comment #13 - Permalink
    Richard
    12/06/2009

    @Tworzenie, :)

  14. Comment #14 - Permalink
    Chang
    12/09/2009

    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.

  15. Comment #15 - Permalink
    Richard
    12/12/2009

    @Chang,

    Please do. Thanks!

  16. Comment #16 - Permalink
    JB
    12/29/2009

    settype($array,’object’)

  17. Comment #17 - Permalink
    Laurie
    01/29/2010

    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.

  18. Comment #18 - Permalink
    piwshop
    02/15/2010

    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.

  19. Comment #19 - Permalink
    Richard
    02/16/2010

    @JB, Thanks for sharing that!

  20. Comment #20 - Permalink
    Richard
    02/16/2010

    @Laurie, Thanks for sharing that!

  21. Comment #21 - Permalink
    Richard
    02/16/2010

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

  22. Comment #22 - Permalink
    v
    03/04/2010

    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.

  23. Comment #23 - Permalink
    Edward Savage
    03/12/2010

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

  24. Comment #24 - Permalink
    Dave Edelhart
    03/14/2010

    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.

  25. Comment #25 - Permalink
    Stas
    06/01/2010

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

  26. Comment #26 - Permalink
    Richard
    06/08/2010

    @Stas, ;)

  27. Comment #27 - Permalink
    Mikkel Juhl
    07/25/2010

    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!

  28. Comment #28 - Permalink
    Webagentur
    08/20/2010

    Thank you, that has me very helped.

  29. Comment #29 - Permalink
    Sag-e-Attar Junaid Atari
    08/26/2010

    Cool, this is what i was looking for.

    Man, Your the rock.

It's Your turn

Click here to cancel reply.
You

CAPTCHA Image
CAPTCHA Audio
Refresh Image



About The Author

Richard is a Web Developer currently working for SankyNet. He is available for freelance work. Visit Shifting Ideas for inquiries. Thanks!
  • Premium Email Templates

    Social Profiles

  • Twitter
  • Facebook
  • LinkedIn
  • Digg
  • Google
  • GitHub

    Last Tweet

  • Beware the heat-seeking Nerf machine-gun coming to a cubicle near you http://om.ly/svHF #fb
  • Follow me
  • Archives

    • August 2010
    • July 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • October 2009
    • September 2009
    • August 2009
    • July 2009
    • June 2009
    • May 2009
    • September 2008
    • August 2008
    • July 2008
    • June 2008
  • Categories

    • AJAX
    • Apache
    • Books
    • Drupal
    • Ecommerce
    • Flash
    • Google
    • Javascript
    • jQuery
    • Magento
    • Marketing
    • Mootools
    • My Thoughts
    • MySQL
    • News
    • Photoshop
    • PHP
    • Prototype
    • SEO
    • Web Resources
    • Wordpress
  • My Favorites

    • 37 Signals
    • Andrew Warner
    • Chris Coyier
    • Chris Shiflett
    • Collis Ta'eed
    • Development Seed
    • Drupal
    • HubSpot
    • James Padolsey
    • Joel On Software
    • John Resig
    • jQuery
    • Kevin Rose
    • Life Hacker
    • Magento
    • Mashable
    • Matt Cutts
    • Matt Ryan
    • MySQL
    • NetTuts
    • Noupe
    • Photoshop Tutorials
    • PHP
    • Smashing Magazine
    • Tech Crunch
    • WoorkUp
    • Wordpress

2010 © Copyright. Richard Castera - All Rights Reserved.

Top