array to object

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I use php 4.3.7,  I can not install/load additional librairies
and I want to convert an array

$a = Array( key1 => value1,
                   key2 => value2);

to an object so I can access array data

$a->key1 or $a->key2

Is there any PHP function or can I create
a function to convert the array to an object ?

Best regards,

Re: array to object

Why do you need to convert an array to an object?

Tony Marston

Quoted text here. Click to load it

Re: array to object

*** Lionel Gondy escribió/wrote (Mon, 20 Sep 2004 19:31:20 +0200):
Quoted text here. Click to load it

This was my first guess and apparently works:


$a=array('key1' => 'value1', 'key2' => 'value2');

class Foo{

    function Foo($array){
        foreach($array as $k => $v){

$b=new Foo($a);

echo $b->key1 . ', ' . $b->key2;


This code prints value1, value2. It doesn't work with regular arrays (only
associative): you can't name a class attribute after a number.

I just wonder why anyone would need to do such a thing... :)

-+ Álvaro G. Vicario - Burgos, Spain
+- (la web de humor barnizada para la intemperie)
++ Las dudas informáticas recibidas por correo irán directas a la papelera
-+ I'm not a free help desk, please don't e-mail me your questions

Re: array to object

de  >
Quoted text here. Click to load it

Thank you for this code.

I will call a function that takes as argument an array of objects
and I can not change this function behavior.


Site Timeline