Last Updated: May 26, 2018
·
3.594K
· leonardodna

"One line" PHP Array to Object

As I can't comment on @buckheroux pro tip, it's always nice to remeber that you can convert an array to an object just typecasting the variable:

$obj = (object) $array;

Clean and straight to the point :)

And the manual for other references:

http://www.php.net/manual/en/language.types.object.php#language.types.object.casting

4 Responses
Add your response

Casting can also convert an object to array
$array = (array) $obj;

over 1 year ago ·

I do this every time I want to create a stdClass out of an array. Except when the array is empty by default, then there's no real time saver over new stdClass;

over 1 year ago ·

simple yet effective.

over 1 year ago ·

Should be noted this DOES NOT work with Multi dimensional array

over 1 year ago ·