tags:

views:

159

answers:

2

I have this function coded to check the status of a Rapidshare link using their API:

function CheckLink($fileid, $filename)
    {
     $q = file_get_contents("http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles_v1&files=$fileid&filenames=$filename");
     $r = explode(",", $q);
     switch ($r[4])
     {
      case 0:
       return array('status' => "0", 'desc' => "File not found");
       break;
      case 1:
       return 1;
       break;
      case 2:
       return 1;
       break;
      case 3:
       return array('status' => "0", 'desc' => "Server down");
       break;
      case 4:
       return array('status' => "0", 'desc' => "File marked as illegal");
       break;
      case 5:
       return array('status' => "0", 'desc' => "Anonymous file locked");
       break;
      case 6:
       return 1;
       break;
      default:
       return array('status' => "0", 'desc' => "Unknown error");
     }
    }

If the function returns 1, the file is alive. If it returns an array it means the file is dead. The array it returns is the status code (0 because it's dead) and the error message to be shown to the user.

Now, I have this code in index.php:

if(is_array($var = CheckLink($match[1], $match[2])))
{
    echo $var[1];
}

What I'm trying to do is check if the result of the function is an array (meaning the link is dead) and if it is, echo the error message to the user. But it's not working, I get no PHP error and it's not echo'ing anything to the page.

Any help on this? Thanks. :)

+5  A: 

There's no key 1 in your result array. Change the echoline to echo $var['desc'].

Edit WRT comment:

No, PHP 'arrays' are more like hash tables: Every value has a key, which is usually numeric, but can be a string (I'd say 'can be anything', but I'm not sure of the extents of what can be a key in PHP). If you don't specify one, it's made to be an integer, automatically-increasing key, so these two arrays are equivalent: array('a', 'b', 'c') and array(0 => 'a', 1 => 'b', 2 => 'c').

There is technically no "second element" to be accessed with [1], because hash tables are unsorted. You can acces a "keyless" array because it's not actually keyless: its key is just automagically defined.

Tordek
Ahah, such a silly mistake. I thought you could reference an array element like that regardless of how the array is structured.Thanks :)
Joseph
This answer looks right. Consider a simpler interface, without the array... just return a String if there's a problem, and 1 otherwise... or go further, and return the error if there is one, and null otherwise... just an idea.
ndp
Joseph, you like this answer accept it by clicking the checkmark to the left.
Mike B
+1  A: 

Did you do a print_r of $var?

$var = CheckLink($match[1], $match[2]);
var_dump(is_array($var));
print_r($var);
meder