1

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?

user13286
  • 3,027
  • 9
  • 45
  • 100

2 Answers2

1

Try use isset to check, example:

$mediaURL = '';
if( isset($tweet['entities']['media'][0]['media_url_https']) ){
   $mediaURL = $tweet['entities']['media'][0]['media_url_https'];
}
Khaled Alam
  • 885
  • 7
  • 12
0

You need to add var_dump($tweet) to see what does $tweet contains. The error means that there is no such key as media in the $tweet['entities'] array (assuming $tweet and $tweet['media'] are both array based on the way you have presented) . After that you can use isset function or Null coalescing operator to check if the key that you are looking for exists or not then take necessary action.

e.g.

$mediaUrl = $tweet['entities']['media'][0]['media_url_https'] ?? ''; 
banstola
  • 47
  • 2