Steven
Steven

Reputation: 19455

Why am I getting error message "Cannot use object of type stdClass as array"?

I have a object $images that looks like this:

stdClass Object
(
    [0] => stdClass Object
        (
            [id] => 125
            [title] => 131301
            [file_name] => 131301
            [file_ext] => jpg
            [dir] => Adventure/
            [fk_gallery_id] => 1
        )

    [1] => stdClass Object
        (
            [id] => 126
            [title] => 181301
            [file_name] => 181301
            [file_ext] => jpg
            [dir] => Adventure/
            [fk_gallery_id] => 1
        )
);

Now I want to get the first element in the object:

$obj = $images[0].

This gives me the error:

Fatal error: Cannot use object of type stdClass as array

Can anyone tell me why this is not working?

I've also tried $images[0]->id, but this is not working either.

Upvotes: 0

Views: 2300

Answers (6)

user252566
user252566

Reputation: 141

Try $image->0->id This might work for your code

Upvotes: 0

Mohit Bumb
Mohit Bumb

Reputation: 2493

Try this:

$a = $image->0;
$id = $a->id

Upvotes: 0

Joyce Babu
Joyce Babu

Reputation: 26

$images is not an array, it is an object of the type StdClass (standard class is actually a dummy class). To access class members, you have to use the format

$object->membername

Unfortunately, 0 is not a valid member name. Hence you cannot use $images->0. The workaround is to use the format

$images->{"0"}

The following will also work (Depending on your PHP version)

$a = 0;
$images->$a;

Upvotes: 1

Vipin Jain
Vipin Jain

Reputation: 1402

Use this as the images is also an object and inside one are also objects

$images->{0}->id;

Upvotes: 0

user142162
user142162

Reputation:

They are class members, therefore you need to access them like this:

$obj = $images->{0};

See: Variable variables.

Upvotes: 3

scibuff
scibuff

Reputation: 13765

try

$obj = $images["0"];

or

$key = 0;
$obj = $images[ $key ];

Upvotes: 0

Related Questions