Error: cannot use object of type stdClass as array error in PHP or Wordpress

Share:
Error: cannot use object of type stdClass as array error in PHP or Wordpress


Many of you facing error "cannot use object of type stdClass as array". In this post you will learn how can we resolve this error? This post will show you when you get this error message and How can you resolve this error easily.

PHP or WordPress shows "cannot use object of type stdClass as array" error message when your code tries to access the Object type variable as an Array. It is possible that you’ve tried to access your object type variable with the generic bracket Array accessor not an object operator. 

See the below example which is able to throw this error.


Example 1: Below example is show an error

You can see in the below example we are trying to access the object type variable using the array. throws an error of “cannot use object of type stdClass as array

 $object = new stdClass();  

 $object->firstVariable = 'My First Value';  

 $object->secondVariable = 'My Second Value';  

 $object->thirdVariable = 'My Third Value';  

 $object->fourthVariable = 'My Fourth Value';  

 echo $object["firstVariable"]; // Error thrown here  

Now you can see the second example without the error

Example 2: Below example does not throw an error

You can see the same example, but in this example, you can see the object variable is using the object operator to show the value. You can see this example is not throw an error

 $object = new stdClass();  

 $object->firstVariable = 'My First Value';  

 $object->secondVariable = 'My Second Value';  

 $object->thirdVariable = 'My Third Value';  

 $object->fourthVariable = 'My Fourth Value';  

 echo $object->firstVariable;  

 OutPut  

 My First Value  


Solutions

We have two different solutions to resolve this issue. 

  1. Convert the object  type variable to an array variable before accessing it with an array 
  2. Access the object type variable values with an object operator as shown in Example

 $object = new stdClass();  
 $object->firstVariable = 'My First Value';  
 $object->secondVariable = 'My Second Value';  
 $object->thirdVariable = 'My Third Value';  
 $object->fourthVariable = 'My Fourth Value';  
 $array = json_decode(json_encode($object), true);  
 echo $array['firstVariable'];  
 OutPut  
 My First Value  



No comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();

Ads