Replacing Do ... While Loops
I have the following piece of code taken from the PHP manual on the curl_multi_* entries:
$active = null;
do {
$process = curl_multi_exec($curl, $active);
} while ($process === CURLM_CALL_MULTI_PERFORM);
while (($active >= 1) && ($process === CURLM_OK))
{
if (curl_multi_select($curl, 3) != -1)
{
do {
$process开发者_开发技巧 = curl_multi_exec($curl, $active);
} while ($process === CURLM_CALL_MULTI_PERFORM);
}
}
Now the thing is I really don't like writing do...while loops and I was wondering what would is the best and shorter way to accomplish the same but without using this kind of loops.
So far I've come up with a slightly longer version but I'm not sure if it does exactly the same or if it performs the same way as the original one:
while (true)
{
$active = 1;
$process = curl_multi_exec($curl, $active);
if ($process === CURLM_OK)
{
while (($active >= 1) && (curl_multi_select($curl, 3) != -1))
{
$process = CURLM_CALL_MULTI_PERFORM;
while ($process === CURLM_CALL_MULTI_PERFORM)
{
$process = curl_multi_exec($curl, $active);
}
}
break;
}
else if ($process === CURLM_CALL_MULTI_PERFORM)
{
continue;
}
break;
}
Thanks in advance.
I don't see a problem with do while loops. They should be used when the code within the loops contains something that should be executed at least 1 time and more times if a condition is met.
IMO, I think your first set of code is clearer.
Do..While
loops are near exact to While
loops, except that they ensure the code within the Do..While
loop executes at least once. So the simple way to convert Do..While
loops is to pull out the code from the Do..While
so that it executes once and convert to While
.
do {
action();
} while(...)
is equivalent to:
action();
while(...) {
action();
}
So applied to your code the change would look like:
$active = null;
$process = curl_multi_exec($curl, $active);
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
}
while (($active >= 1) && ($process === CURLM_OK))
{
if (curl_multi_select($curl, 3) != -1)
{
$process = curl_multi_exec($curl, $active);
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
};
}
}
With that said, there's nothing wrong with Do..While
loops and you should use them if you need to.
Will this do?
$active = null;
$process = curl_multi_exec($curl, $active);
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
};
$process = curl_multi_exec($curl, $active);
while (($active >= 1) && ($process === CURLM_OK)) {
if (curl_multi_select($curl, 3) != -1) {
while ($process === CURLM_CALL_MULTI_PERFORM) {
$process = curl_multi_exec($curl, $active);
}
}
}
精彩评论