Skip to main content
February 11, 2010
Answered

Limit a while loop

  • February 11, 2010
  • 1 reply
  • 699 views

Is there a way to write this where it will limit the number of times that it runs - say 20 times?

while($p_link = array_search("0", $links))

   {        

      $links[$p_link] = "1";

// do this

}

This topic has been closed for replies.
Correct answer David_Powers

If you do get some time, can you explain this:

num_results = ($num_results > 20) ? 20 : $num_results;

Not sure I understand the ? 20 : $num_results; part.

Thanks


It uses the ternary operator.

1 reply

Participating Frequently
February 11, 2010

Coming from a non php coder...most languages allow you to include more than one condition in a while loop. So initialize a counter variable that you increment within the loop. And (not sure of the AND operator in php) it with the other condition. Something like:

$counter=0

while($p_link = array_search("0", $links) && $counter <20)

   {        

      $links[$p_link] = "1";

      $counter++

// do this

}

David_Powers
Inspiring
February 11, 2010

We'll make a PHP coder of you yet.

The only thing that's wrong is the semicolon missing from the end of each statement:

$counter=0;

while($p_link = array_search("0", $links) && $counter <20)

{        $links[$p_link] = "1";

  $counter++;

// do this

}

February 11, 2010

Thank you, I just could not figure this out as I wanted to add an entirely new while loop.  However, this still is not giving me the results I want.

What I have is code that will get all the internal links from a url, parse through those links for certain content (set by the preg_match_all($search, $contents, $search_results)), then add that content to an array ($gold).

However, I want to limit the number of links that it parse through to say 20 links.

Using the information your provider earlier ($counter) – it skips the parsing through the links and just seems to skip over the get content and following code.

I have tried putting the counter in other places or even using additional while loops but have gotten nowhere.  Can you tell me where I should be trying to limit the number of links to parse?

Code is attached