user3263155
user3263155

Reputation: 203

php foreach/for acting weirdly

Someone can solve this mystery? i have two code samples. I think that the second example does same thing as first example but apparently it doesnt.

this works:

 print_r($this->facebook->my_retrieve_timeline()['data'][0]->message);
print_r($this->facebook->my_retrieve_timeline()['data'][2]->message);

this doesnt:

for ($i=0; $i <11; $i++) { 
        echo $this->facebook->my_retrieve_timeline()['data'][$i]->message;
    }

error:

Message:  Undefined property: stdClass::$message

array looks like this:

Array
(
[data] => Array
    (
        [0] => stdClass Object
            (

                [message] => bbbbbbbbb

            )

        [1] => stdClass Object
            (


                [lol] => aaaaaaaaa
            )
        [2] => stdClass Object
            (

                [message] => ccc

            )


    )
)

EDIT, SOLVED: so the only problem was that i didnt have message property inside of every object

Upvotes: 0

Views: 45

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Your error is because you are trying to access the object property message when it doesn't exist. Also, not an error in this case, but you are also assuming that array indexes 0-10 exist, which might not be the case.

Loop through only valid/existing array elements and check if the message property exists before accessing it:

foreach($this->facebook->my_retrieve_timeline()['data'] as $data) {
    if(property_exists($data, 'message')) { // or use isset($data->message)
        echo $data->message;
    }
}

This doesn't make assumptions about which numeric keys exist (loops only existing elements) and also checks if message property exists before accessing it. As a bonus, it only calls my_retrieve_timeline() once instead of every loop iteration.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Why did you think they'd be the same? The first example accesses array elements 0 and 1; the second accesses 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Clearly at least one of those elements does not exist, given the error message you receive.

There is also a difference between print_r and echo.

Upvotes: 1

Related Questions