PHP : Array to Object

Tue, May 6, 2008

PHP

I wrote a quick and simple function which allows you to quickly convert arrays to objects. It allows you to change an array like this :

$a[‘b’];

To an object like this :

$a -> b;

Below is the function. Have fun!

<?php

function array_to_object($array = array()) {
    if (!empty($array)) {
        $data = false;

        foreach ($array as $akey => $aval) {
            $data -> {$akey} = $aval;
        }

        return $data;
    }

    return false;
}

?>

, , ,

This post was written by:

Antonie Potgieter - who has written 57 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

22 Comments For This Post

  1. patrick Says:

    function array_to_object($array = array()) {
    return (object) $array;
    }

  2. lost-in-code Says:

    @patrick

    Thank you for the type casting example. It is useful!

  3. Hari Says:

    This will not work with multi dimensional arrays.

  4. Antonie Potgieter Says:

    @Hari

    You are right, it will not work with multi-dimensional arrays.
    You could create a recursive type of function with a break to handle that though.
    Below is an example of how the array is converted to an object.

    http://lost-in-code.com/wp-content/projects/php-array-to-object/

    The example I wrote above uses type casting.
    Either way, it only converts the first array instance and not the inner arrays.

    Best,
    Antonie

  5. james lyttelton Says:

    or just use:

    $object = (object)$array;

  6. Antonie Potgieter Says:

    @james

    Yes, that was the type casting method which was mentioned earlier. Its a quick way of doing it. The function in the article simply illustrates the “core” of such a function and is a good reference for writing a recursive function/method to convert multi-dimensional arrays.

  7. james lyttelton Says:

    yes ok, thank you. very interesting.

    what do the curly brackets actually do under the covers there? {$akey}

  8. Antonie Potgieter Says:

    @james

    The curly brackets create variable variables.
    It basically creates a variable with the name of the variable inside the brackets.

    Let me give you an example. You have a variable $a with the value “b” and a variable $b with the value “a”. You could output the contents of the variable $b like this :

    ${$a}

    You can read more about it here : http://www.php.net/language.variables.variable

    All the best,
    Antonie

  9. james lyttelton Says:

    ok, thanks. I’ll go and twist my head round a lamppost and look at it again and I’m sure it’ll make more sense!

    ok, done, understood now and I’m sure some poor sod reading some of my old spaghetti code would have benefited from me knowing that!

    all the best,

  10. Antonie Potgieter Says:

    @james

    Yeah, you can often benefit from it by creating more dynamic code. If you ever need some PHP assistance, feel free to hit me up on Skype as “Contrid”. Two minds are better than one and I have a good feel for the language.

    Best,
    Antonie

  11. Mihai Stancu Says:

    I wrote a class for allmost the same purpose.

    I only meant to manypulate the initial array “as” an object. Not convert it entirely.

    My purpose was to control arrays like $_SESSION in an objectual manner, while not having to convert them into local objects and the back into arrays.

    It is fully recursive.

    And uses PHP magic functions for most of the job.

    class Array_Object
    {
    private $init;
    function __construct(&$init)
    {
    if(empty($init))
    session_start();
    if(!empty($init))
    $this->init = &$init;
    }
    function __get($name)
    {
    if(empty($name))
    return $this->init;
    else
    if(is_array($this->init[$name]))
    if($this->$name)
    return $this->$name;
    else
    return $this->$name = new session($this->init[$name]);
    else
    return $this->init[$name];
    }
    function __set($name,$value)
    {
    if(get_class($value) == “session” && !empty($name))
    $this->$name = &$value;
    else if(empty($name))
    $this->init = &$value;
    else
    if(is_array($value))
    {
    $this->$name = new session($value);
    $this->init[$name] = &$value;
    }
    else
    $this->init[$name] = &$value;
    }
    function __unset($name)
    {
    unset($this->$name);
    }
    function __destruct()
    {
    unset($this);
    }
    function index($no)
    {
    return $this->init[$no];
    }
    }

  12. mgsmus Says:

    objects are always good to me :

    $db->tableName->fieldName;
    $db->tableName->recordCount();

    i don’t use $rsarray['fieldName'] anymore :)

  13. Me Says:

    Nevermind, crappy message posting system. Geez, can’t seem to share my way of doing this.

  14. ThomasR Says:

    For multidimensionnal arrays :

    function object_to_array($mixed) {
    if(is_object($mixed)) $mixed = (array) $mixed;
    if(is_array($mixed)) {
    $new = array();
    foreach($mixed as $key => $val) {
    $key = preg_replace(“/^\(.*)\/”,”",$key);
    $new[$key] = object_to_array($val);
    }
    }
    else $new = $mixed;
    return $new;
    }

  15. Jay Williams Says:

    I’ve built my own array to object function, which uses references for optimal speed and memory usage. And it also supports multi-dimensional arrays.

    You can see the code here: http://gist.github.com/257606

    I’m thinking it would be even faster than the code you have posted.

  16. Lennard Schutter Says:

    Multidimensional worked for me though:

    $obj = (object)array(“mood” => (object)array(“happy” => “lol”, “angry” => “grr”),”color” => (object)array(“blue” => “cold”, “red” => “hot”));

    print $obj->mood->angry;

    Thanks for this post btw! Was really helpfull!

  17. ecommerce website Says:

    I’m using the following:

    foreach ($all as $value)
    {
    echo $value.”;
    }

  18. carabain Says:

    Nice snippet Antonie.
    Here’s a recursive version i created:

    function toObject($array) {
    $obj = new stdClass();
    foreach ($array as $key => $val) {
    $obj->$key = is_array($val) ? toObject($val) : $val;
    }
    return $obj;
    }

  19. CodeBoxer Says:

    How do you deal with numeric arrays?

  20. web development Says:

    in terms of performance which is better, object or array?

  21. shaffy Says:

    Good Programming..

  22. shaffy Says:

    good programming

1 Trackbacks For This Post

  1. Массив в объект на php Says:

    [...] Оригинал: на lost-in-code.com [...]

Leave a Reply