0

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.

1
  • Because you have an object and not an array... like the error message says. Commented Apr 16, 2012 at 12:40

6 Answers 6

3

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

$obj = $images->{0};

See: Variable variables.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha.Thanks, I didn't know that. This removes the error. But doing a print_r($obj)shows nothing. And echo $obj->title also shows nothing.
1

$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;

5 Comments

Yes, $tim-cooper already explained this. But it's not working for me. See my comment.
my bad. you need to use $images->{"0"}
Thanks, that worked like a charm. - Actually, I was a bit too quick. The result is the same - I get nothing.
Try this code. Is it working? $tmp = json_decode('{"0": [1, 2, 3]}'); print_r($tmp->{"0"});
If that works, then the problem is not with the code. Check $images and ensure that id is not empty. Are you getting any notices? try setting error_reporting(E_ALL | E_NOTICE);
0

try

$obj = $images["0"];

or

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

Comments

0

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

$images->{0}->id;

Comments

0

Try this:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.