I have a cycle, but sometimes it goes into infinite execution. Is it possible to somehow make it so that if the cycle is performed longer than 2х секунд then change the variables $l_dict and $r_dict to $l_dict = 'dict' and $r_dict = 'dict'

  do { $word_1 = changeRegister($l_dict); $word_2 = changeRegister($r_dict); $check = checkUpperRegister($word_1) && checkUpperRegister($word_2); } while ($check); $summa = $p_1.$word_1.$p_2.$word_2.$p_3; $password = preg_replace('/\s+/u', '', $summa); $check_lentgh = mb_strlen($password, 'UTF-8') == $glength; } while (!$check_lentgh); 
  • And why through set_time_limit ()? Maybe using time ()? - Edward
  • four
    Recalled one old story - Ipatiev
  • @ Edward is not necessarily set_time_limit (), I didn’t know about time () :) - Nikolai Vasilenkov
  • Hint: if the password generation takes more than one millionth of a second, perhaps something should be corrected in the algorithm. - Ipatiev
  • @ Nikolai Vasilenkov "cycle, but sometimes it goes into infinite execution" how is it like that? )) But it is not better to find and correct the cause than to look for methods to correct the consequences .... - Arsen

2 answers 2

I would limit on the number of so

 if(++$i == 100) break; 

But if you really need time

 $max = 1000; //maximum time in milliseconds $start = microtime(true); foreach($tasks as $t) { if (microtime(true) - $start > $max) { break; } } 

    First, decide which problem you are trying to solve. After all, if you think about it, it will turn out that she is in a friend:

    Sometimes in the $ r_dict and $ r_dict dictionaries there are no words that together will not exceed $ glength

    As a result, the question is quite different. Like the solution. For example, in your case, you can add words to dictionaries by length. Take a random dictionary with words of any length. Get a random word from this dictionary. Now subtract from your limit on the length of the password the length of the selected word (dictionary), get the rest, which will be equal to the length of the word (dictionary) that remains to be added to the password. Go to the dictionary of this length and take out a random word from there. In total, they will be guaranteed to give the desired length. The solution will turn out in one iteration, which means no cycles at all.