phpundefined-index

Twitter API undefined PHP index


I am using this Twitter API code to display tweets on my website. Currently I am getting "undefined index" PHP errors, which do not affect functionality but I would like to know the correct way to resolve them anyway. I am guessing I need to check if a response from the Twitter API exists first, before defining the variable, but not sure the correct way to go about that.

Here's a sample of the code:

$id = $tweet['id'];
$formattedTweet = !$isRetweet ? formatTweet($tweet['full_text']) : formatTweet($retweet['full_text']);
$statusURL = 'http://twitter.com/' . $userScreenName . '/status/' . $id;
$date = timeAgo($tweet['created_at']);
$mediaURL = $tweet['entities']['media'][0]['media_url_https'];

Let's say, for example, that a returned tweet does not have an image, I will then get the error Notice: Undefined index: media in ... from the $mediaURL variable. How can I resolve this?


Solution

  • Try use isset to check, example:

    $mediaURL = '';
    if( isset($tweet['entities']['media'][0]['media_url_https']) ){
       $mediaURL = $tweet['entities']['media'][0]['media_url_https'];
    }