DEV Community

Cover image for Convert an Array To StdClass With PHP
Programming Dive
Programming Dive

Posted on

Convert an Array To StdClass With PHP

For more details, click on this link.

To Convert an Array to stdClass 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 PHP.

What is stdClass in PHP?

stdClass stands for standard Class

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
class nature{}
$objNature= new nature();
if ($objNature instanceof stdClass){
    echo 'Yes';
} else {
    echo 'No';
}
Enter fullscreen mode Exit fullscreen mode
// OUTPUT

No

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.

  • Using Typecast
  • Using custom function
  • Using json_encode() and json_decode()

Solution 1: Using typecast/ Type Juggling

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
$empInfo = array(
    'name'=>'John',
    'address'=>'Houston',
);
$empInfoObj = (object) $empInfo;
print_r($empInfoObj);
Enter fullscreen mode Exit fullscreen mode
// OUTPUT

stdClass Object 
(
   [name] => John 
   [address] => Houston 
)

Here, we defined an array $empInfo 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 $empInfoObj->name 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
$empInfo = array(
    'name'=>'John',
    'address'=>'Houston',
    'employment' => array(
        'id' => '1',
        'address' => 'Los Angeles'
        )
);
$empInfoObj = (object) $empInfo;
print_r($empInfoObj);
Enter fullscreen mode Exit fullscreen mode
// OUTPUT

stdClass Object 
( 
[name] => John 
[address] => Houston 
[employment] => Array 
     ( 
         [id] => 1 
         [address] => Los Angeles 
     ) 
)

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.

Solution 2: Using custom function

<?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));
Enter fullscreen mode Exit fullscreen mode
// OUTPUT

stdClass Object 
( 
   [name] => John 
   [address] => Houston 
   [employment] => stdClass Object 
      ( 
         [id] => 1 
         [address] => Los Angeles 
      ) 
)

Here, in the above example, we have recursively called toObject() function to check the innermost array present (if any) and then typecast it into an object.

Solution 3: Using json_encode() and json_decode()

json_encode() and json_decode() are the functions especially for performing operations on JSON string.

json_encode()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 json_decode().

<?php
$empInfo = array(
'name'=>'John',
'address'=>'Houston',
'employment' => array(
    'id' => '1',
    'address' => 'Los Angeles'
    )
);
print_r(json_decode(json_encode($empInfo)));
Enter fullscreen mode Exit fullscreen mode
// OUTPUT

stdClass Object
(
   [name] => John
   [address] => Houston
   [employment] => stdClass Object
      (
         [id] => 1
         [address] => Los Angeles
      )
)

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.

Conclusion:

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.

Top comments (2)

Collapse
 
mkhuramj profile image
Khuram Javed

This really is one of the terrible things PHP has, that's why I am trying to move to NodeJS.
I think when the PHP had released type casting from array to object, why they had left such most wanted thing???

Collapse
 
rk610 profile image
rk610 • Edited

How can i get title and url according tags PHP

  stdClass Object
        (  
                 [title] => Title 1
                 [url] => title-1
                 [tags] => Array
                   (
                       [0] => stdClass Object
                          (
                            [A/B/C] => a/b/c
                         )        
                   )
               [monster_branche] => 
      )
    stdClass Object
         (  
                [title] => Title 2
                [url] => title-2
                [tags] => Array
                      (
                           [0] => stdClass Object
                               (
                                  [BT] => Bt
                               )
                      )
               [monster_branche] => 
        )
Enter fullscreen mode Exit fullscreen mode