无法从函数中回显变量

时间:2014-11-29 05:29:03

标签: php function url curl foreach

我正在尝试ping网址,如果成功返回变量中的URL密钥。 无论网址是什么,我都会在功能之外使用它。

function findUrl(){
    $links = array(
        'www.anyurl.com/ping'  => 'www.anyurl.com',
        'www-01.anyurl.com/ping' => 'www-01.anyurl.com',
        'www-02.anyurl.com/ping' => 'www-02.anyurl.com',
        'www-03.anyurl.com/ping' => 'www-03.anyurl.com'
    );
    foreach($links as $value => $key){
        $ch = curl_init($value);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($httpcode>=200 && $httpcode<300){
            echo $value; // Does ehco Ping URL
            echo $key; // Does echo URL
            exit;
        } else {echo "Not successful."}
    };
    echo "didn't work" . "<br>";
}
findUrl(); // run function
echo $value; // Doesn't return URL. But i somehow need it.

1 个答案:

答案 0 :(得分:1)

您不希望exit想要returnexit终止整个脚本。

return $value;

然后,当您调用该函数时,您需要接收返回的值:

$val = findUrl();
echo $val;