Notice: Undefined offset

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Notice: Undefined offset

Post by Live24x7 »

This is the code for a wordpress function to grab the first post image and return it.

Code: Select all



function catch_that_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;

}
	
Now this was to be used as Image like this:

Code: Select all

 <img width="120px" height="120px"src="<?php echo catch_that_image() ?>" >.

Strangely I am getting a notice that reads:

Notice: Undefined offset: 0 in C:\wamp\www\wordpress\wp-content\themes\GM\functions.php on line 58 Call Stack #TimeMemoryFunctionLocation .

FYI: Line 58 in the above code is $first_img = $matches [1][0];

I googled all over the place but could not fix this.

Any suggestions ? And what exactly does undefined offset mean ?

Thanks
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Notice: Undefined offset

Post by requinix »

What is the value of $output?

Undefined offset $X[Y] means that the array X does not have a key Y. In your case $matches[1] does not have a first element. Which implies that...
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Notice: Undefined offset

Post by Live24x7 »

thanks for the explanation - this helped me figure out & correct the issue.
Posting the corrected code so that some googler someday might find it useful :)

Code: Select all

function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_img = $matches [1] [0];
return $first_img;
}
else {
$first_img = get_template_directory_uri()."/images/default.jpg";
return $first_img;
}
}
Post Reply