How to avoid PHP Notice “Undefined offset: 0” without checking each field of array

后端 未结 5 1163
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 03:27

i have the following array:

    $keyvisual_data = array(
        \'video_file\'            => $row->field_field_video[0][\'rendered\'][\'#item\'][\'uri\'],         


        
5条回答
  •  生来不讨喜
    2021-02-05 03:33

    You could add a shorthand check if each value is null

    $default_value = "Default value";
    
    $keyvisual_data = array(
            'video_file' => ($row->field_field_video[0]['rendered']['#item']['uri'] == null) ? $default_value : $row->field_field_video[0]['rendered']['#item']['uri']
    
    // etc.. etc...
    );
    

    A less messy version of this, to explain the code more clearly:

     ($video_file == null) ? $default_value : $video_file
    );
    
    // Will output "I am a Default value"
    echo $new_array['video_file'];
    ?>
    

提交回复
热议问题