0

I am trying to get the variable $matches to be usable outside of this function. So I can use echo $matches[0][0]; or $matches[0][1]; after the function gets used in my document. So far I haven't been able to use the matches variable outside of the function at all.

    function curlLink($url, $regex)
{
        include ('lib/dBug.php');
        require_once('lib/curl_http_client.php');
        $curl = &new Curl_HTTP_Client();
        //$useragent = "Googlebot/2.1 (+http://www.google.com/bot.html)";  
        $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0";
        $curl->set_user_agent($useragent);
        ini_set('max_execution_time','0');
        $x=0;
        $matches = array();
        while (sizeof($matches) == 0 && $x < 15) {
            $html_data = $curl->fetch_url($url);
            preg_match_all($regex, $html_data, $matches); 
            $x++;
            array_shift($matches);
        }
        if (empty($matches[0][0])) {
            echo '<img src=\"/img/bigbrokenlink.png\" /><br /><br />
            <b>Sorry, no results from your search!</b><br />';
        }
        if (!empty($matches[0][0])) {
            //return $matches; //This doesn't seem to return a usable variable...
            $dBug = new dBug ($matches);
        }
}

3 Answers3

1

declare $matches = array(); outside of function as global variable.or return it to some function and use.

e.g.:

global $matches;
function curlLink($url, $regex)
{
    global $matches;
// implementation 
}

//access here $matches;

Suchit kumar
  • 11,448
  • 3
  • 17
  • 41
1

Set the variable as global by the following example:

global $matches;
function curlLink($url, $regex)
{
    global $matches;

or return it after the call, it seems you are not returning anything right now.

        if (!empty($matches[0][0])) {
            //return $matches; //This doesn't seem to return a usable variable...
            $dBug = new dBug ($matches);
        }
        return $matches;
}
$returned_matches = curlLink($url, $regex);
Unamata Sanatarai
  • 5,609
  • 3
  • 22
  • 46
0

You can make it global, but that's probably not wanted. What you should do is:

  • change the first line to function curlLink ($url, $regex, &$matchesOut)

  • at the end of function, use $matchesOut = $matches

  • you can now use:

$matches = array(); curlLink(arg1, arg2, $matches); echo $matches[0];

  • I'd like to try this solution, but I can't seem to get this to work. Nor could I find documentation on using &$var in a function. – James Lyngaas Sep 28 '14 at 21:25
  • Even if you can't get it to work, do NOT use global vars. http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – Adrian Hussel Sep 28 '14 at 21:27
  • Here are docs; http://php.net/manual/en/functions.arguments.php#functions.arguments.by-reference – Adrian Hussel Sep 28 '14 at 21:28