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.

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

 

51 thoughts on “PHP – Convert Array to Object with stdClass”

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

    Please check out with:

    {syntaxhighlighter brush: php}$person = array (

    ‘first’ => array(‘name’ => array(‘first_name’ => ‘Richard’, ‘last_name’ => ‘Castera’))

    );{/syntaxhighlighter}

    Thanks

  2. Great post!

    Just discovered that

    {syntaxhighlighter brush: php}

    $a = (object)mysql_fetch_assoc();

    {/syntaxhighlighter}

    is faster than

    {syntaxhighlighter brush: php}

    $a = mysql_fetch_object();

    {/syntaxhighlighter}

  3. 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:

    {syntaxhighlighter brush: php}

    public function makeObjects($data) {

    $object = (object) $data;

    foreach ($object as $property) {

    if (is_array($property)) $this->makeObjects($property);

    }

    return $object;

    }

    {/syntaxhighlighter}

    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.

  4. You can also define your own class:

    {syntaxhighlighter brush: php}

    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;

    }

    }

    }

    {/syntaxhighlighter}

    Then use it like this:

    {syntaxhighlighter brush: php}

    $array = array( ‘a’ => ‘abc’, ‘b’ => ‘xyz’, ‘c’ => array(‘one’ => 1, ‘two’ => 2) );

    $obj = new arrayClass( $array );

    print $obj->c->one; //prints ‘1’

    {/syntaxhighlighter}

  5. 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!

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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!

  12. 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:

    {syntaxhighlighter brush: php}

    static public function array2Object($aArray)

    {

    return is_array($aArray) ? (object)array_map(‘Type::array2Object’, $aArray) : $aArray;

    }

    {/syntaxhighlighter}

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

    {syntaxhighlighter brush: php}

    $aTest = array(‘field1’, ‘field2’, ‘field3’);

    $oTestInt = Type::array2Object($aTest);

    $oTestString = Type::array2Object(array_fill_keys($aTest, ”));

    {/syntaxhighlighter}

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

  13. 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:

    {syntaxhighlighter brush: php}

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

    {/syntaxhighlighter}

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

    {syntaxhighlighter brush: php}

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

    ?>

    {/syntaxhighlighter}

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

    {syntaxhighlighter brush: php}

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

    ?>

    {/syntaxhighlighter}

    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!

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

    {syntaxhighlighter brush: php}$example = $wpdb->get_results(“SELECT * FROM wp_posts WHERE ID= ’20′”);

    print_r($example);{/syntaxhighlighter}

    returns something like

    {syntaxhighlighter brush: php}Array ( 0 => stdClass Object ([id] => 20, [post_name] => example, …) ){/syntaxhighlighter}

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

  15. 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 🙁

    any help would be greatly appreciated…

  16. 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/”;

  17. 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; } } ?>

  18. 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)));

    ?>

  19. É mais fácil assim oh…

    private function arrayToObject($Array){

    if (is_array($Array)) {

    foreach ($Array as $Key => $Value){

    if (is_array($Value)){

    $Array[$Key] = (object) $this->arrayToObject($Value);

    }

    }

    }

    return (object) $Array;

    }

    código limpo e sem brecha pra erro..

    bele?

    um abraço…

  20. You saved my life with this! I’m newish to PHP, and the “->” operator was driving me nuts! (Try searching for “->” on Google sometime, you’ll see what I mean!)

    Thanks!

  21. Hi,

    I am using this code from 2 years and this morning I found a bug 😉

    If the name of the array is zero [0], array_to_object() skip that array. For example in this array:

    Array

    (

    [arData] => Array

    (

    [0] => Array

    (

    [data1] => d1

    [data2] => d2

    )

    [1] => Array

    (

    [data1] => d1

    [data2] => d2

    )

    )

    The result after used array_to_object() is:

    Array

    (

    [arData] => Array

    (

    [1] => Array

    (

    [data1] => d1

    [data2] => d2

    )

    )

    To fix this, replace

    < ?php if (!empty($name)) { ?>

    to

    < ?php if ( (string) $name != '' ) { ?>

    Many thanks Richard for your help with this code 😀

    Rémi

Leave a Reply

Your email address will not be published. Required fields are marked *