PHP - undefined offset: 0

后端 未结 2 556
盖世英雄少女心
盖世英雄少女心 2021-01-06 04:29

print_r($p->attachments) produces:

Array
(
    [0] => stdClass Object
        (
            [id] => ...
            [url] => http://         


        
相关标签:
2条回答
  • 2021-01-06 05:23

    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

    0 讨论(0)
  • 2021-01-06 05:33

    dunno why it returns you a value and informs you that there is undefined offset 0. strange.

    can you check this (since attachments is an array you should do this that way):

    if ( count($p->attachments) > 0 ){ 
       foreach ($p->attachments AS $att){
        //do the stuff if attachement 
       }
    }
    
    0 讨论(0)
提交回复
热议问题