Convert an Array To StdClass With PHP
Published: 2020-11-19 08:08:38

For more details, <a href="https://programmingdive.com/convert-an-array-to-stdclass-with-php/">click on this link</a>.

To Convert an Array to <a href="https://www.php.net/manual/en/language.types.object.php">stdClass</a> with PHP is an easy step. In this tutorial, we will use different ways using which we can easily achieve the desired outcome.

Before jumping right into the solution, let's understand a few things about stdClass is in <a href="https://programmingdive.com/category/php/">PHP</a>.

<h3>What is stdClass in PHP?</h3>
<blockquote>
stdClass stands for standard Class
</blockquote>
stdClass is just a generic empty class in PHP OR we can say it’s PHP’s class prototype like Object.prototype in JavaScript, Object in Java OR object in Python.

Here, point to be noted that despite generic class, stdClass is NOT the base class for objects in PHP and we can prove this using instanceof keyword.
```php
<?php
class nature{}
$objNature= new nature();
if ($objNature instanceof stdClass){
    echo 'Yes';
} else {
    echo 'No';
}
```
<pre>
// OUTPUT

No
</pre>
This clarifies that stdClass is not the base class for objects in PHP.

Now, we will see different ways useful to convert an array to stdClass.

3 different ways to convert array to stdClass.
<ul>
<li>Using Typecast</li>
<li>Using custom function</li>
<li>Using json_encode() and json_decode()</li>
</ul>
<h4>Solution 1: Using typecast/ Type Juggling</h4>
Typecasting an array to a stdClass object is the easiest way to achieve. It will convert value of one data type into another data type.
```php
<?php
$empInfo = array(
    'name'=>'John',
    'address'=>'Houston',
);
$empInfoObj = (object) $empInfo;
print_r($empInfoObj);
```
<pre>
// OUTPUT

stdClass Object 
(
   [name] => John 
   [address] => Houston 
)
</pre>
Here, we defined an array <code>$empInfo</code> in which we defined 3 keys and associated values and in the next line, we typecast our array into an object using the name of the desired type, written in parentheses before the variable which is to be cast.

We can now access the property of the object with object-oriented style syntax as <code>$empInfoObj->name</code> which will output John.

This is the simplest solution to our problem. But what if the array is multidimensional? Does the above solution work? And the answer is NO.

Let’s update our $empInfo array.
```php
<?php
$empInfo = array(
    'name'=>'John',
    'address'=>'Houston',
    'employment' => array(
        'id' => '1',
        'address' => 'Los Angeles'
        )
);
$empInfoObj = (object) $empInfo;
print_r($empInfoObj);
```
<pre>
// OUTPUT

stdClass Object 
( 
[name] => John 
[address] => Houston 
[employment] => Array 
     ( 
         [id] => 1 
         [address] => Los Angeles 
     ) 
)
</pre>
As we can see, an array defined inside the employment key does not get converted to a stdClass. So, type juggling casts the values at the opt level keys and not the keys which are defined in a nested pattern.

So, here we can write our customize function to solve the problem.

<h4>Solution 2: Using custom function</h4>
```php
<?php
function toObject($arr) {
    if (is_array($arr)) {
        // Return object 
        return (object) array_map('toObject', $arr);
    }
     return false;
}
$empInfo = array(
    'name'=>'John',
    'address'=>'Houston',
    'employment' => array 
        (
           'id' => '1',
           'address' => 'Los Angeles'
        )
);
print_r(toObject($empInfo));
```
<pre>
// OUTPUT

stdClass Object 
( 
   [name] => John 
   [address] => Houston 
   [employment] => stdClass Object 
      ( 
         [id] => 1 
         [address] => Los Angeles 
      ) 
)
</pre>
Here, in the above example, we have recursively called <code>toObject()</code> function to check the innermost array present (if any) and then typecast it into an object.

<h4>Solution 3: Using json_encode() and json_decode()</h4>
<code>json_encode()</code> and <code>json_decode()</code> are the functions especially for performing operations on JSON string.

<code>json_encode()</code is used to convert an Array into JSON string and <code>json_encode()</code is used to convert a JSON string into an Array.

So, first, we’ll convert an object into a JSON string and then will convert it into an object using <code>json_decode()</code>.
```php
<?php
$empInfo = array(
'name'=>'John',
'address'=>'Houston',
'employment' => array(
    'id' => '1',
    'address' => 'Los Angeles'
    )
);
print_r(json_decode(json_encode($empInfo)));
```
<pre>
// OUTPUT

stdClass Object
(
   [name] => John
   [address] => Houston
   [employment] => stdClass Object
      (
         [id] => 1
         [address] => Los Angeles
      )
)</pre>
Instead of writing a custom function, we can use these in-built functions to get the desired output and also we don’t need to worry about the innermost array element as these two functions will take care of them.

<h3>Conclusion:</h3>
These 3 ways of Converting an Array To StdClass With PHP gives better options depending upon the requirement. Mostly in today's web frameworks we commonly deal with class hierarchy. So converting an array into stdClass at runtime will be a better option.