• Hi,
    While I am trying to get the first image in the post with this code,

    function get_the_first_image()
    {
      global $post, $posts;
      $image = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $image = $matches[1][0];
      if(empty($image)) {
        $image = get_option('defaultthumbnail');
      }
      return $image;
    }

    I am getting a PHP Notice that Notice: Undefined offset: 0 in Line 8, i.e the line with $image = $matches[1][0];.

    I know I can safely ignore this notice as this is not going to show with DEBUG mode disabled.

    But, is there any way to fix that notice? I tried my level best, also searched Google for fixes, but none of them helped much.

    I’d really appreciate any help here.

    Regards

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    I assume you only get this if no image URL match is found, such that the default thumb is used instead. In any case, to avoid a notice when this happens, you need to check if the $matches element is set or if the number of matches is not zero before trying to assign the $matches element.

Viewing 1 replies (of 1 total)
  • The topic ‘HELP "Notice: Undefined offset: 0"’ is closed to new replies.