Skip to content

Convert Array To Object With PHP

Converting array to object with PHP is merely simple for normal array , bit complicated for multidimensional array. Here i will show you different methods for converting array to object.

Using Type Casting

This method will work as expected with normal arrays(single dimension array).

$data = (object)array('India','UK','US','England');
print_r($data);
//output : stdClass Object ( [0] => India [1] => UK [2] => US [3] => England ) 

Using array_map()

This method will work with multidimensional and single dimension arrays.

 array('UP','AP'),'UK','US','England');

$object = (object)array_map(function($item) { return is_array($item) ? (object)$item :  $item;  }, $array);

print_r($object);

// output : stdClass Object ( [India] => stdClass Object ( [0] => UP [1] => AP ) [0] => UK [1] => US [2] => England ) 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments