Invert while results

Posted on

Coding Problem :

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

Answer :


Answer 1 :

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>';
}

    


Answer 2 :


Answer 3 :


Answer 4 :


Answer 5 :


Answer 6 :


Answer 7 :


Answer 8 :


Answer 9 :

Leave a Reply

Your email address will not be published. Required fields are marked *