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;
}

?>

, , ,
scriptlancebannerpng

This post was written by:

Antonie Potgieter - who has written 46 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

4 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

Leave a Reply