PHP Notice: Undefined offset: 0 fixable?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



PHP Notice: Undefined offset: 0 fixable?



I have a "get first image script" I am using that is all over the internet but am getting the error:



PHP Notice: Undefined offset: 0



the script is:


function get_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];
return $first_img;



can this be fixed?





Possible duplicate of Notice: Undefined offset: 0 in
– Alex W
Aug 7 at 19:18





Use print_r($matches); to see what matches are available. Use isset() or empty() to first check it's available.
– Rasclatt
Aug 7 at 19:20


print_r($matches);


isset()


empty()




3 Answers
3



Based on your regex this could happen if the <img> tag has no src attribute or if there are no <img> tags at all.


<img>


<img>



As others have suggested you could fix this by checking $matches first, but I'd like to suggest an alternate approach that may be more robust for parsing html in php, since using regex to do this is discouraged.


$matches


function get_first_image()
global $post;
$first_img = '';
$dom = new DOMDocument();
$dom->loadHtml($post->post_content);
foreach ($dom->getElementsByTagName('img') as $img)
if ($img->hasAttribute('src'))
$first_image = $img->getAttribute('src');
break;


return $first_img;



The above function uses php's DOMDocument Class to iterate over <img> tags and get the src attribute if it exists. (Note: I removed the ob_start() and ob_end_clean() functions from your code because I don't understand what purpose they were serving)


<img>


ob_start()


ob_end_clean()



You can do this:


$first_img = isset($matches[1][0]) ? $matches[1][0] : false;



Which will, then, return false if the first position in this two dimension array would not exist.



Before operator:


$first_img = $matches [1] [0];



insert the line:


var_dump($matches);



Make sure, that $matches is an array, and has two dimensions.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS