Reverse results of while

Asked

Viewed 261 times

5

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

For example, I have the following code that checks whether 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;
    }
}
?>

He brings me the URL’s as follows, I would like the result to be from the largest to the smallest but I don’t know if with my current code I could.

inserir a descrição da imagem aqui

1 answer

9


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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.