Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Two Ways To Convert Array To StdClass With PHP

Converting an Array to a StdClass object is super-simple with PHP. Using a type casting method you can quickly carry out an array to StdClass conversion in one line of code. Alternatively, you can harness the power of PHP’s encoding functions such as json_encode and json_decode.

In this tutorial, two of the alternate methods of converting an array to a fully operating object will be demonstrated.

Method 1: Type Casting with (object)

In the first method, we virtually hit the array on the head with a hammer and force a typecast conversion. First of all, we will need an array, let’s define an associative array of data first.

Array

$myArray = ["usersOnline" => 76, "registeredUsersOnline" => 21, "website" => "codewall"];

Next, we hit the variable on the head with a virtual object hammer to cast it to a StdClass.

PHP Conversion

$myStdClass = (object) $myArray;

var_dump($myStdClass);

Output

object(stdClass)#1 (3) { ["usersOnline"]=> int(76) ["registeredUsersOnline"]=> int(21) ["website"]=> string(8) "codewall" }

This conversion leaves us able to access the object with object-oriented style syntax, for example –

echo $myStdClass->usersOnline; // outputs 76

Method 2: Convert using encoding functions

In the second and alternative method, we will utilise the JSON encoding functions that PHP holds. Again, using the same simple array –

Array

$myArray = ["usersOnline" => 76, "registeredUsersOnline" => 21, "website" => "codewall"];

With the array, we first parse it into a JSON string with json_encode and finally, decode the string with the json_decode function.

PHP Conversion

$myStdClass = json_decode(json_encode($myArray));

var_dump($myStdClass);

Output

object(stdClass)#1 (3) { ["usersOnline"]=> int(76) ["registeredUsersOnline"]=> int(21) ["website"]=> string(8) "codewall" }

And again, we can utilise the object style syntax to access the values via their relative keys.

echo $myStdClass->website; // outputs codewall

And that is it, two super slick one-liners to convert an array into a fully operable StdClass object.

The post Two Ways To Convert Array To StdClass With PHP appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

Two Ways To Convert Array To StdClass With PHP

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×