1

The code I wrote supposed to do two things: 1- shows the latest post from a twitter user 2- searches for a specific keyword. For the first part, it works perfectly but it fails in case of 'search' option by dumping this error message:

PHP Notice: Undefined offset:

I run the code with this format:

$ php script.php search keyword number

Here is the code:

    $result = file_get_contents("http://search.twitter.com/search.json?q=$argv[2]&rpp=$argv[3]&include_entities=true&result_type=mixed");
    $decoded = json_decode($result,true);
    for($j=0; $j<$argv[3]; $j++)
    {

    echo ($decoded[$j]['text']);



   }
2
  • 1
    that error is just a notice it wont stop the code from running, what it means though is that ur trying to use probably an array that hasnt been set, best thing would be print_r(); whatever arrays your using and see if the contain what they're suppose to Commented Apr 15, 2013 at 1:30
  • Probably the array doesn't contain anything. You should check with isset or something. What exact line is the error on? Commented Apr 15, 2013 at 1:30

2 Answers 2

3

I've checked the Twitter response, it doesn't match the format of the array you trying to access. You can't access the data through $decoded[$j]['text'] simply because that doesn't exist in the response.

What you mean to do is:

$decoded[results][$j]['text']

I've checked it and that appears to works fine.

Excerpt from the response (print_r format), you see why it happens.

Array (
  [completed_in] => 0.015
  [max_id] => 322818055665225728
  [max_id_str] => 322818055665225728
  [page] => 1
  [query] => testsearch
  [refresh_url] => ?since_id=322818055665225728&q=testsearch&result_type=mixed&include_entities=1
  [results] => Array
    (
      [0] => Array
        (
          [created_at] => Fri, 12 Apr 2013 21:06:36 +0000
          [entities] => Array
Sign up to request clarification or add additional context in comments.

Comments

0

If the user inputs '10' but the query only returns 9 results, the 10th iteration of the for loop will return that notice (as $decoded[9] doesn't exist).

Perhaps try something like this

$limit = $argv[3];

if (count($decoded) < $limit)
{
    $limit = count($decoded);
}

for ($j = 0; $j < $limit; $j++)
{
...
}

1 Comment

Probably true, but it is not the root cause of the problem here. He should implement something like this, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.