Invert while results

5

Is there a function in PHP that allows me to reverse the order of results of a while ?

For example, I have the following code that checks for a URL.

<?php
function url_exists($url) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ($code == 200); 
}

$noticia=700;

while($noticia)
{
    if (url_exists($url = 'http://www.exemplo.com.br/noticia_'.$noticia.'.htm'))
    {
        echo '<a href="'.$url.'">'.$url.'</a><br>';
        $noticia++;
    }
    else{
        break;
    }
}
?>

It brings me the URL's as follows, I'd like the result to be from the highest to the smallest but I do not know if my current code would do it.

    
asked by anonymous 14.01.2015 / 16:46

1 answer

8

You can store the result in an array and then invert it:

$arrUrls = array();
while($noticia)
{
    if (url_exists($url = 'http://www.exemplo.com.br/noticia_'.$noticia.'.htm'))
    {
        $arrUrls[] = $url;
        $noticia++;
    }
    else{
        break;
    }
}

foreach (array_reverse($arrUrls) as $url) {
    echo '<a href="'.$url.'">'.$url.'</a><br>';
}
    
14.01.2015 / 16:54