Array2object and Object2array

Convert an associative array to an anonymous object and vice versa.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function array2object($array) {
 
    if (is_array($array)) {
        $obj = new StdClass();
 
        foreach ($array as $key => $val){
            $obj->$key = $val;
        }
    }
    else { $obj = $array}
 
    return $obj;
}
 
function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}
 
 
// example:
 
$array = array('foo' => 'bar''one' => 'two''three' => 'four');
 
$obj = array2object($array);
 
print $obj->one// output's "two"
 
$arr = object2array($obj);
 
print $arr['foo']// output's bar
X

Url: http://www.jonasjohn.de/snippets/php/array2object.htm

Language: PHP | User: ShareMySnippets | Created: Oct 16, 2013