Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - undefined offset: 0

Tags:

arrays

object

php

print_r($p->attachments) produces:

Array
(
    [0] => stdClass Object
        (
            [id] => ...
            [url] => http://...png
            [slug] => ...
            [title] => ...
            [description] => ...
            [caption] => ...
            [parent] => ...
            [mime_type] => image/png
            [images] => ...
                (
                )
        )
)

I wish to access the value in the url field

print_r($p->attachments[0]->url) retrieves the url, but also produces: Undefined offset: 0

Now I can supress the error by calling print_r(@$p->attachments[0]->url), but is there a proper way of fixing this?

I am not able to modify the $p object.

Edit:

As suggested, here is response from Var_dump($p->attachments)

 array(1) {
  [0]=>
  object(stdClass)#322 (9) {
    ["id"]=>
    int(1814)
    ["url"]=>
    string(76) "..."
    ["slug"]=>
    string(34) "..."
    ["title"]=>
    string(34) "..."
    ["description"]=>
    string(0) ""
    ["caption"]=>
    string(53) "..."
    ["parent"]=>
    int(1811)
    ["mime_type"]=>
    string(9) "image/png"
    ["images"]=>
    array(0) {
    }
  }
}
like image 684
Gravy Avatar asked Sep 18 '13 19:09

Gravy


1 Answers

You can use isset() for check the array:

if(isset($p->attachments[0])){
    echo $p->attachments[0]->url;
}
else {
  //some error?
}

Or if you know that you are only going to be checking index 0 then you can do this way

$array = $array + array(null);

So if the original $array[0] was unset, now it is null

like image 187
Suvash sarker Avatar answered Oct 02 '22 11:10

Suvash sarker