[php] PHP Error: Cannot use object of type stdClass as array (array and object issues)

I was trying to copy this code:

<?php
foreach ($products as $product) {
    $id          = $product['id'];
    $name        = $product['name'];
    $description = $product['description'];
    $price       = $product['price'];
?>
    <tr>
    <td><img src="<?php echo $product['picture']; ?>" /></td>
        <td><b><?php echo $name; ?></b><br />
        <?php echo $description; ?><br />
          Price:<big style="color:green">
          $<?php echo $price; ?></big><br /><br />
<?php
    echo form_open('cart/add');
    echo form_hidden('id', $id);
    echo form_hidden('name', $name);
    echo form_hidden('price', $price);
    echo form_submit('action', 'Add to Cart');
    echo form_close();
?>
    </td>
    </tr>
    <tr><td colspan="2"><hr size="1" /></td>
<?php
}
?>

and here is my code:

<?php
   foreach ($blogs as $blog) {
      $id      = $blog['id'];
      $title   = $blog['title'];
      $content = $blog['content'];
?>
      <h1><?php echo $title; ?></h1>
      <h1> <?php echo $content; ?> </h1>

<?php
}
?>

I get this error every time I run my code: "Cannot use object of type stdClass as array"

This question is related to php arrays object

The answer is


The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.


$blog is an object not an array

try using $blog->id instead of $blog['id']


$blog is an object, not an array, so you should access it like so:

$blog->id;
$blog->title;
$blog->content;

There might two issues

1) $blogs may be a stdObject

or

2) The properties of the array might be the stdObject

Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this

$blog->id;
$blog->content;
$blog->title;

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.


StdClass object is accessed by using ->

foreach ($blogs as $blog) {
    $id         = $blog->id;
    $title  = $blog->title;
    $content    = $blog->content;
}

Questions with php tag:

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop? Target class controller does not exist - Laravel 8 Message: Trying to access array offset on value of type null Array and string offset access syntax with curly braces is deprecated Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error How to fix "set SameSite cookie to none" warning? The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac What does double question mark (??) operator mean in PHP Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client php mysqli_connect: authentication method unknown to the client [caching_sha2_password] Converting a POSTMAN request to Curl Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Issue in installing php7.2-mcrypt Xampp localhost/dashboard How can I run specific migration in laravel How to change PHP version used by composer Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Artisan migrate could not find driver phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO) Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) laravel 5.5 The page has expired due to inactivity. Please refresh and try again "The page has expired due to inactivity" - Laravel 5.5 How to increment a letter N times per iteration and store in an array? Can't install laravel installer via composer Only on Firefox "Loading failed for the <script> with source" Is there way to use two PHP versions in XAMPP? How to prevent page from reloading after form submit - JQuery laravel Eloquent ORM delete() method No Application Encryption Key Has Been Specified General error: 1364 Field 'user_id' doesn't have a default value How to logout and redirect to login page using Laravel 5.4? How to uninstall an older PHP version from centOS7 How to Install Font Awesome in Laravel Mix PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers Laravel - htmlspecialchars() expects parameter 1 to be string, object given How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Questions with arrays tag:

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with object tag:

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor How to iterate (keys, values) in JavaScript? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Check if value exists in the array (AngularJS) How to write data to a JSON file using Javascript Why is "forEach not a function" for this object? How to remove undefined and null values from an object using lodash? Creating a static class with no instances What is the difference between ( for... in ) and ( for... of ) statements? How do I print my Java object without getting "SomeType@2f92e0f4"? How can I return the difference between two lists? How do I correctly setup and teardown for my pytest class with tests? Javascript - removing undefined fields from an object Python iterating through object attributes How to iterate through an ArrayList of Objects of ArrayList of Objects? transform object to array with lodash What's the difference between integer class and numeric class in R Check if object value exists within a Javascript array of objects and if not add a new object to array How to get the difference between two arrays of objects in JavaScript Mapping a JDBC ResultSet to an object javascript find and remove object in array based on key value How to create multiple class objects with a loop in python? How to delete an instantiated object Python? How can I remove an element from a list, with lodash? JavaScript: Create and destroy class instance through class method Zoom to fit: PDF Embedded in HTML Creating multiple objects with different names in a loop to store in an array list Creating object with dynamic keys Get specific object by id from array of objects in AngularJS How to parse JSON with VBA without external libraries? iterating through json object javascript How to get the hours difference between two date objects? How to sort an array of objects in Java? how to use javascript Object.defineProperty Get specific objects from ArrayList when objects were added anonymously? How to copy JavaScript object to new variable NOT by reference? error C2220: warning treated as error - no 'object' file generated passing object by reference in C++ Get values from an object in JavaScript How to convert a string to JSON object in PHP Parse JSON response using jQuery