skip to Main Content

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?

2

Answers


  1. 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'] ?? ''; 
    
    Login or Signup to reply.
  2. Try use isset to check, example:

    $mediaURL = '';
    if( isset($tweet['entities']['media'][0]['media_url_https']) ){
       $mediaURL = $tweet['entities']['media'][0]['media_url_https'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search