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