Undefined Offset 0 error in PHP

Discussion in 'PHP' started by riteshsanap, Feb 16, 2012.

  1. #1
    Hello,
    I was developing my WP theme so i wrote a Piece of Script that will retrieve First Image from the Post, well the Script works just fine, but it generates Error when i turn on WP_DEBUG the error is :

     Notice: Undefined offset: 0 in C:\wamp\www\wp-content\themes\zeenet\functions.php on line 72
    Code (markup):
    Here is the code written :
    function first_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[/'"]([^/'"]+)[/'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      }
      return $first_img;
    }
    Code (markup):
    well the error returns on the line of
    $first_img = $matches [1] [0];
    Code (markup):
    according to the above code, that line is 72th in my functions.php
     
    Solved! View solution.
    riteshsanap, Feb 16, 2012 IP
  2. #2
    **You're definitely getting that error because this value doesn't not exist >>> $matches [1] [0]

    I'm assume the script works at times, and then sometimes you get the error? Am I right??
    I can't imagine how you said the code works perfectly, because where it stands currently, I THINK you're actually pulling the SECOND image from the post. Are you sure the script pulls the first image?? :confused:

    $matches [0] should be used for pulling the first image as far as I can tell and $matches [1] for the second. However, if there's only one image, then $matches [1] won't be existing, hence the error.
     
    Andre91, Feb 16, 2012 IP
  3. riteshsanap

    riteshsanap Well-Known Member

    Messages:
    217
    Likes Received:
    2
    Best Answers:
    3
    Trophy Points:
    168
    #3
    he bro thanks, i changed
    $first_img = $matches [1] [0];
    Code (markup):
    to
    $first_img = $matches [1];
    Code (markup):
    well i don't know why the original writer of the script added array [0] BTW still thanks
     
    riteshsanap, Feb 16, 2012 IP
  4. Andre91

    Andre91 Peon

    Messages:
    197
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    0
    #4
    Yes, I have no idea why the original author uses a multi-dimensional array. Cuz it doesn't exist.
     
    Andre91, Feb 16, 2012 IP
  5. riteshsanap

    riteshsanap Well-Known Member

    Messages:
    217
    Likes Received:
    2
    Best Answers:
    3
    Trophy Points:
    168
    #5
    Can you give me a nice guide about arrays ?
     
    riteshsanap, Feb 16, 2012 IP
  6. Andre91

    Andre91 Peon

    Messages:
    197
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    0