Note that there are some explanatory texts on larger screens.

plurals
  1. PORandom string avoiding words in array behaving incorrectly
    text
    copied!<p>I found some unexpected behavior in my code, so made two examples to demonstrate what was happening and couldn't figure things out from there. What I found was odd to me, and perhaps I'm missing something.</p> <p><strong>Goal: Create a random string and avoid anything specified in an array.</strong></p> <p>In the examples below, I have two methods of testing this.</p> <p>First I have a function that creates a random string from specified characters ($characters) and then I have an array ($avoid) (here with double letters specified) which then loops and informs you if the code worked and it indeed found what was specified in the array.</p> <p>This seems to work, however then I modified the second function to attempt to generate a new random string if the same trigger happened. This to avoid having a string with anything in the array.</p> <p>This part doesn't seem to work.. I'm not sure how else to modify it from here, but I must be missing something. Running the code works, but it catches some things and misses other times.. which I wouldn't expect from code.</p> <pre><code>function getrandom($loopcount) { $loopcount++; $length = 20; $characters = 'abc'; $string = ''; for ($p = 0; $p &lt; $length; $p++) $string.= $characters[ mt_rand( 0,strlen($characters) ) ]; $avoid = array( 'aa', 'bb', 'cc' ); foreach ($avoid as $word) if ( stripos($string,$word) ) $string = 'Double '.$word.' Detected:'.$string; return '&lt;h1 style="color:blue;"&gt;'.$string.'&lt;h1&gt;'; } echo getrandom(0); echo getrandom(0); echo getrandom(0); function getrandom2($loopcount) { $loopcount++; $length = 20; $characters = 'abc'; $string = ''; for ($p = 0; $p &lt; $length; $p++) $string.= $characters[ mt_rand( 0,strlen($characters) ) ]; $avoid = array( 'aa', 'bb', 'cc' ); foreach ($avoid as $word) if ( stripos($string,$word) ) $string = getrandom2($loopcount); return '&lt;h1 style="color:green;"&gt;'.$string.'&lt;h1&gt;'; } echo getrandom2(0); echo getrandom2(0); echo getrandom2(0); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload